All posts

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:

No types written
let username = "John Snow";
let username: string
let age = 24;
let age: number
let isAlive = true;
let isAlive: boolean

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:

An inferred object type
const person = {
const person: {
    id: number;
    name: string;
}
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:

Build an array, watch the type
Add an item
TypeScript infers

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:

Array or tuple?
const guessed = ["Robb Stark", 26];
const guessed: (string | number)[]
const student: [string, number] = ["Robb Stark", 26];
const student: [string, number]

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:

Why it matters
const const guessed: (string | number)[]guessed = ["Robb Stark", 26];
const age: number = const guessed: (string | number)[]guessed[1];
Type 'string | number' is not assignable to type 'number'. Type 'string' is not assignable to type 'number'.

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:

An inferred return type
function addFive(x: numberx: number) {
function addFive(x: number): 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:

Type from the surrounding code
const const names: string[]names = ["Ayesha", "Kiraak"];

const names: string[]names.Array<string>.forEach(callbackfn: (value: string, index: number, array: string[]) => void, thisArg?: any): void
Performs the specified action for each element in an array.
@paramcallbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.@paramthisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
forEach
((name: stringname) => {
var console: Consoleconsole.Console.log(...data: any[]): void
The **`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(): string
Converts all the alphabetic characters in a string to uppercase.
toUpperCase
());
name: string
});

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:

Tell TypeScript what goes in
const const items: number[]items: number[] = [];

const items: number[]items.Array<number>.push(...items: number[]): number
Appends new elements to the end of an array, and returns the new length of the array.
@paramitems New elements to add to the array.
push
(1);
const items: number[]items.Array<number>.push(...items: number[]): number
Appends new elements to the end of an array, and returns the new length of the array.
@paramitems New elements to add to the array.
push
("John");
Argument of type 'string' is not assignable to parameter of type 'number'.

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.

🧩 Your turn

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.

🎉 Nice! No type errors. TypeScript is happy now.

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.