Skip to content
jshacks.dev
TypeScript

Type Inference in TypeScript

TypeScript works out most types for you. Learn how inference treats let and const, arrays, return values and callbacks, and when to write a type yourself.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the TypeScript, npm and Node.js logos.

Beginners often expect TypeScript to mean annotating everything, and then they open a well-written codebase and find that most variables have no annotation at all. The compiler is working out the types on its own. This is type inference, and it is the reason TypeScript code can look so close to plain JavaScript while still being checked. This post explains how inference works for variables, arrays, objects, function return values and callbacks, shows the exact errors that reveal the inferred types, and gives rules for when to rely on inference and when to write a type yourself. It uses TypeScript 6.x, and the rules are described in the type inference page of the handbook.

Inference from initial values

The simplest case is a variable with an initial value. The compiler takes the type of the value and gives it to the variable.

basics.tsTypeScript
let count = 0;
count = "many";

The variable was never annotated, yet the second line is an error:

Text
basics.ts(2,1): error TS2322: Type 'string' is not assignable to type 'number'.

From let count = 0 the compiler inferred number, and later assignments must respect it. You wrote no type, but the variable is as protected as if you had. Hovering over count in an editor shows let count: number, which is the quickest way to see what the compiler decided.

let and const infer differently

A let variable can change, so the compiler widens a literal to its general type. A const variable cannot change, so the compiler keeps the narrowest type it can, the literal itself.

literals.tsTypeScript
let a = "hello";
const b = "hello";

a = "goodbye";
b = "goodbye";
Text
literals.ts(5,1): error TS2588: Cannot assign to 'b' because it is a constant.

The error here comes from const itself, but the inferred types differ. a has type string, so the assignment on line 4 is fine. b has the literal type "hello", a type that contains exactly one value. You can see the difference when you pass the variables to a function that requires the literal.

widen.tsTypeScript
function setMode(mode: "light" | "dark") {
  return mode;
}

const chosen = "dark";
let typed = "dark";

setMode(chosen);
setMode(typed);
Text
widen.ts(9,9): error TS2345: Argument of type 'string' is not assignable to parameter of type '"light" | "dark"'.

The const keeps the literal "dark", which fits the union, so line 8 passes. The let was widened to string, which does not, so line 9 fails. This surprises people because the two variables hold the same value. The fix is to declare the variable as const, or annotate it as let typed: "light" | "dark" = "dark". When a literal union should survive, const is the simplest answer.

Arrays and objects

For arrays, the compiler infers the element type from the contents. An array of numbers is number[], and an array that mixes types gets a union.

arrays.tsTypeScript
const nums = [1, 2, 3];
const mixed = [1, "two", 3];

nums.push("four");
mixed.push(true);
Text
arrays.ts(4,11): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
arrays.ts(5,12): error TS2345: Argument of type 'boolean' is not assignable to parameter of type 'string | number'.

The first error is for pushing a string into number[]. The second shows the union: the inferred type of mixed is (string | number)[], so a string or number would be accepted, and the boolean is not. Inference for object literals works the same way: each property gets the inferred type of its value, so { name: "Ana", age: 31 } has the type { name: string; age: number }. Properties are widened because object properties are mutable.

An empty array is a special case. The compiler cannot see any elements, so const items = [] starts with an unsettled element type that the compiler works out from later pushes, and it can report an error when it cannot settle on one. When you start with an empty collection, annotate it: const items: string[] = []. This is one of the clearest cases where writing the type is better than relying on inference.

Return types

The compiler also infers what a function returns, by looking at its return statements.

returns.tsTypeScript
function area(width: number, height: number) {
  return width * height;
}

const size = area(2, 3);
const label: string = size;
Text
returns.ts(6,7): error TS2322: Type 'number' is not assignable to type 'string'.

The function has no return annotation, but width * height is a number, so area returns number and size is a number. The error on line 6 shows that the inferred type flows through. When a function has several return statements, the result is a union of their types, so a function that returns a string in one branch and undefined in another is inferred as string | undefined.

Should you annotate return types anyway? For exported functions in a library, yes, because the return type is part of the public contract and an accidental change in the body should not silently change it. For private helpers and short callbacks, inference keeps the code light. A common team rule is to annotate function parameters always, annotate exported return types, and infer the rest.

Contextual typing

The most useful form of inference runs the other way. When you pass a function to something that already has a type, the compiler infers the parameters of your function from that context. This is called contextual typing.

context.tsTypeScript
const names = ["ana", "ben", "cy"];

const lengths = names.map((name) => name.length);
const bad = names.map((name) => name.toFixed());
Text
context.ts(4,38): error TS2339: Property 'toFixed' does not exist on type 'string'.

You did not annotate name. The compiler knows names is string[], so the callback passed to map receives a string, and name.length is valid while name.toFixed() is not. The same mechanism types event handlers, promise callbacks and anything you pass to a typed API. It is why annotating callback parameters is usually unnecessary, and why adding annotations there can be redundant noise.

Contextual typing has a limit. It applies when the function is written in place. If you define the function separately first, there is no context, so its parameters need annotations or they become implicit any, which strict mode reports as an error. When you extract a callback into a named function, add the parameter types.

When to write the type yourself

Inference is good at describing what a value is. It is less good at describing what you intend it to be. Write a type in these cases.

Annotate function parameters, because the compiler has nothing to infer from at the declaration. Annotate empty collections and variables declared without a value, such as let result: Config | undefined. Annotate the public return types of exported functions, to lock the contract. Annotate when the inferred type is wider than you want, for example const mode: "light" | "dark" = "dark" on a let, or when it is too complicated to read in an error message and a named type would help.

An annotation also acts as a check. If you write const user: User = loadUser(), the compiler verifies that the call returns something assignable to User, and later changes to loadUser that break the contract are reported at that line. Without the annotation the variable silently takes whatever type the function now returns, and the error shows up wherever it is used.

Inference and strict mode

Inference gets more useful when strict is on. Without it, the compiler falls back to any in places where it cannot decide, and an any quietly switches checking off for everything that touches it. With strict, those places become errors, such as a parameter with no context and no annotation, and the error tells you to add the type. That is a good trade: the compiler infers what it can, and it stops and asks when it cannot. If you are converting a JavaScript project, turn strict on early, so you learn where inference works and where it needs help while the codebase is still small.

Seeing what was inferred

When an inferred type is not what you expected, ask the compiler. In an editor, hover over the name. On the command line, a trick that works anywhere is to assign the value to a type you know is wrong, such as const probe: never = value, and read the error, which prints the inferred type: Type 'string' is not assignable to type 'never'. Remove the line afterwards. A second option is the satisfies operator, which checks a value against a type without widening what is inferred, so you keep the precise literal types and still get a check.

Share

Keep reading

Flat illustration of an editor window full of code, with the TypeScript, Node.js, npm, Vite and JavaScript logos.
TypeScript

What Is TypeScript, and Why Use It?

TypeScript adds static types to JavaScript and checks them before your code runs. Learn what it is, what it catches, what it costs and when to use it.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.