In this video, you followed the types through Spoke & Sprocket’s parts total for a brake job and saw how much the checker works out with only one annotation in the file. Every annotation is one more thing to update when the code changes, so you write only the ones the checker needs.
Key Points
- Type inference is the checker working out a type from a value.
const brakeJob = [1899, 799];has no annotation, but its value is an array of numbers, so its type isnumber[]. - Hover to confirm. Hover over a name in your editor, and the tooltip shows the type the checker inferred, such as
const brakeJob: number[]. - Types flow from one name to the next. Because
pricesis anumber[],.reduce()passes numbers to its callback, sosumandpriceare numbers. Their types come from where the callback is passed..reduce()on an array of numbers, starting from0, gives back a number, so the checker infers the return type ofpartsTotal()asnumber, andtotal, set from that result, is anumbertoo. - A callback’s return type shapes the result. The callback that
brakeJob.map()gets on thelabelsline returns a string, so.map()builds astring[]forlabels. - Watch out for
letwith a single value: aconstholding a single string or number keeps that exact value as its type (const size = "700x28c"gives"700x28c"), while aletwidens it (tostring), because aletcan change later. So aletcan’t go where only certain exact values are allowed. - Write the type yourself in three places:
- A function’s own parameters. A parameter’s value arrives only when someone calls the function. Without
: number[]onprices, the check reports an implicitanyforpricesand for both callback parameters. A callback’s parameters are different: they get their types from where it’s passed. - Exported functions’ returns. Inference finds
numberhere too, but a written return type is a promise to the files that import the function. Without it, a change like.toFixed(0)quietly changes the inferred type, and the error turns up inquote.ts. With it, the error shows up inparts.ts, where the change is. - Arrays and variables that start empty. An empty array has no values yet, so annotate it with what it’s meant to hold, like
const reorderList: (string | number)[] = [];. The same goes for a variable declared without a value, like thelet rate: number;you wrote in Annotating Functions and Variables, where the rate got its value later in one of two branches. - Everywhere else, let inference do the rest. When a value already gives the type you mean, an annotation only repeats what the checker knows. An annotation that says more than the value, like the
[string, number]tuple for a booking, stays.
The Code
With one annotation, the checker infers every other type in the file: