TypeScript · Lesson 5 of 42
Type annotations and type inference
Learn when to write a type annotation and when TypeScript infers the type for you, including literal types, return types and contextual typing.
UNDERSTAND IT. THEN TRY IT.
What you can do after this lesson
You will know the two ways a value gets a type: you write it, or TypeScript works it out. Most good TypeScript uses both, with annotations where they help and inference everywhere else.
Annotations
A type annotation is a colon and a type placed after a name:
const title: string = "Dune";
let pages: number = 412;
let finished: boolean = false;
console.log(title, pages, finished);Dune 412 falseAnnotations are promises the compiler enforces. If you later try to put the wrong kind of value in, it stops you:
let pages: number = 412;
pages = "many";example.ts(2,1): error TS2322: Type 'string' is not assignable to type 'number'.Inference
Writing the type every time is unnecessary when the compiler can see the value. This code has no annotations, yet it is fully checked:
let count = 0;
count = "five";example.ts(2,1): error TS2322: Type 'string' is not assignable to type 'number'.The compiler inferred that count is a number from the starting value 0. That is called type inference. The error message is the same as before, because the variable has the same type either way.
const versus let
The inferred type depends on whether the variable can change. A let variable might be reassigned, so TypeScript picks the general type. A const variable cannot change, so TypeScript keeps the exact value as its type, called a literal type:
const direction = "north";
const other: "south" = direction;example.ts(2,7): error TS2322: Type '"north"' is not assignable to type '"south"'.The message shows that direction has the type "north", not just string. Literal types matter a great deal later, when you restrict a value to a few allowed options. The key point now is that inference is precise.
Return types are inferred too
A function's return type is worked out from its return statements:
function pick(flag: boolean) {
return flag ? "yes" : 0;
}
const answer: string = pick(true);example.ts(5,7): error TS2322: Type 'string | number' is not assignable to type 'string'.
Type 'number' is not assignable to type 'string'.The function returns a string in one case and a number in the other, so its inferred return type is the union string | number. Assigning it to a string variable fails, because it might be a number. Unions get their own lesson soon. Notice that you never wrote that return type; the compiler built it for you.
Contextual typing
Sometimes a type comes from where a function is used, not from the function itself. This is contextual typing:
const prices = [10, 20, 30];
const labels = prices.map(p => "$" + p.toFixed(2));
console.log(labels);[ '$10.00', '$20.00', '$30.00' ]Nobody annotated p. Because prices is a number[], the callback given to map must receive numbers, so p is a number, and toFixed is available. If you call a string method on it, the editor and compiler stop you.
When to write an annotation
A good rule of thumb:
- Always annotate function parameters. There is no value to infer from. (Callbacks passed directly to functions like
mapare the exception, thanks to contextual typing.) - Annotate return types on exported or public functions. It documents the function and stops an accidental change in what it returns from spreading unnoticed.
- Annotate variables that start empty or are assigned later.
let total: number;orconst items: string[] = [];, because there is nothing to infer from yet. - Let inference do the rest.
const name = "Asha"needs no: string. Extra annotations add noise and can hide a more precise inferred type.
Common mistakes
Annotating everything. const count: number = 0 is noise. If you read code and the annotation tells you nothing the value does not, remove it.
Assuming let and const are the same. const mode = "dark" has the literal type "dark". let mode = "dark" is a plain string. This matters when passing the variable somewhere that wants specific strings.
Forgetting annotations on parameters. In strict mode, a parameter without a type is an error (implicitly has an 'any' type).
Fighting inference. If the compiler infers something you did not expect, check your values. The inferred type is often showing you a real mistake.
Exercise
Write five variables without annotations: a number, a string, a boolean, an array of numbers and an object with two fields. Hover over each in your editor to see its inferred type. Then try assigning a value of the wrong type to each, and read the message. Finally, write a function average(values) and decide which parts need annotations and which you can leave to inference. Compare with function average(values: number[]).
Next: TypeScript primitive types: string, number, boolean and friends.
KNOWLEDGE CHECK
A quick check. You’ve got this.
Try each question. Every answer comes with an explanation.
Ready for the next small win?
Mark the lesson complete when you are ready.