Type Inference in TypeScript
You don't have to write a type for everything. See how TypeScript works out types from your values, where it gets it wrong, and when you should step in and write the type yourself.
How does TypeScript know the type of a variable when you never wrote one?
It looks at the value you gave it and works the type out for you. This is called type inference, and it’s why most TypeScript code has far fewer type annotations than you might expect.
Simple values
Hover over (or tap) each variable. There isn’t a single type annotation in this code, yet every variable has a type:
let username = "John Snow";let age = 24;let isAlive = true;TypeScript saw "John Snow" and decided username is a string. The same goes for the number and the boolean. Writing let username: string = "John Snow" would add nothing, because TypeScript already knows.
Objects
It works for objects too. TypeScript looks at every property and builds the whole shape:
const person = { id: numberid: 1,
name: stringname: "John",
};Because person now has a known shape, TypeScript will stop you if you use a property that doesn’t exist, like person.email, or give person.id a string.
Arrays
For arrays, TypeScript looks at every item and finds a type that fits all of them. Add some items below and watch the inferred type change:
With only numbers, it’s a number[]. Add a string and the type grows into a union: (string | number)[], an array where any item can be a string or a number. Now try turning the tuple type on.
The tuple trap
A tuple is an array with a fixed length, where each position has its own type. A student’s name and age is a perfect example: a string first, a number second.
But TypeScript doesn’t guess tuples. Hover over both versions:
const guessed = ["Robb Stark", 26];
const student: [string, number] = ["Robb Stark", 26];The first one is just a (string | number)[]. As far as TypeScript knows, the age could be a string, and there could be ten items. So this fails:
const const guessed: (string | number)[]guessed = ["Robb Stark", 26];
const age: number = const guessed: (string | number)[]guessed[1];Bottom-up and top-down
So far, every type came from the value on the right-hand side. TypeScript starts from the values and works up to the variable. This is bottom-up inference.
Function return types work the same way. You typed the parameter, but not the return value. Hover over addFive:
function addFive(x: numberx: number) { return x: numberx + 5;
}TypeScript sees x + 5, knows x is a number, so the function returns a number.
Inference can also go top-down: when TypeScript already expects a certain type from the surrounding code, it pushes that type down into what you write. Here, forEach knows it’s working on an array of strings, so the name parameter gets its type without you writing it:
const const names: string[]names = ["Ayesha", "Kiraak"];
const names: string[]names.Array<string>.forEach(callbackfn: (value: string, index: number, array: string[]) => void, thisArg?: any): voidPerforms the specified action for each element in an array.forEach((name: stringname) => {
var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(name.String.toUpperCase(): stringConverts all the alphabetic characters in a string to uppercase.toUpperCase());});A common mistake: empty arrays
An empty array gives TypeScript nothing to infer from. If you only want numbers in it, say so when you create it:
const const items: number[]items: number[] = [];
const items: number[]items.Array<number>.push(...items: number[]): numberAppends new elements to the end of an array, and returns the new length of the array.push(1);
const items: number[]items.Array<number>.push(...items: number[]): numberAppends new elements to the end of an array, and returns the new length of the array.push("John");Without : number[], TypeScript would happily let "John" in next to the 1, and you’d find the bug much later.
Your turn
birthday needs a number, but TypeScript thinks student[1] could be a string. Fix the error by changing one line, then press Run. It should print 27.
Hint: TypeScript inferred an array. What type should student really have?
const student = ["Robb Stark", 26];
function birthday(age: number) {
return age + 1;
}
console.log(birthday(student[1]));Click the code to edit it. TypeScript checks it as you type.
Quick recap
- Type inference means TypeScript works out types from your values, so you don’t write them everywhere.
- It works for simple values, objects, arrays and function return types.
- Mixed arrays become unions, like
(string | number)[]. - TypeScript never infers tuples: write
[string, number]yourself. - Bottom-up inference starts from values. Top-down inference pushes an expected type into your code.
- For empty arrays, always write the type.