Sub topic 3
How TypeScript infers types
This chapter assumes you can write basic JavaScript and run TypeScript with tsc or an editor that shows types on hover. It also assumes you know what string, number, and boolean are. The examples assume "strict": true in tsconfig.json, which is the setting most projects use.
What inference is
Type inference is the compiler working out a type from the code around a value, so you don't have to write it. You can annotate every variable, but most of those annotations repeat what the compiler already knows.
let count = 0; // inferred as number
const name = "Ada"; // inferred as the literal type "Ada"
let items = [1, 2, 3]; // inferred as number[]
count = 5; // ok
// count = "five"; // Error: Type 'string' is not assignable to type 'number'.The inferred type is a real type. Assigning "five" to count fails just as it would with an explicit : number. Inference saves typing and gives up no safety.
The difference between count and name comes from let versus const. The next chapter covers it in detail. For now, remember that the compiler picks a type based on whether the variable can change.
Where inference happens
TypeScript infers types in four main places.
- Variable initializers. The type of the right-hand side becomes the type of the variable.
- Return types. The compiler collects every
returnexpression in a function and combines their types. - Default parameter values.
function greet(name = "world")makesnameastring. - Callback parameters. The expected type of the callback supplies the parameter types. This is contextual typing, covered in a later chapter.
Function parameters without a default are the notable gap. The compiler has no code to look at, so it can't infer them.
function add(a: number, b: number) {
return a + b; // return type inferred as number
}
function greet(name = "world") {
return `Hello, ${name}`; // name: string, return type: string
}If you leave off : number on a in add, the compiler reports Parameter 'a' implicitly has an 'any' type. That error comes from the noImplicitAny option, which is part of strict.
Inferring from structures
For compound values, the compiler infers each piece.
const user = { id: 1, name: "Ada", tags: ["math", "code"] };
// { id: number; name: string; tags: string[] }
const mixed = [1, "two", null];
// (string | number | null)[]Two rules are worth knowing.
- Object properties widen. Even when
useris aconst,idis anumber, not1. Theconststops you reassigninguser. It doesn't freeze its properties, so the compiler assumes they may change. - Array elements combine into a union. The element type of
mixedis the union of every element's type. TypeScript doesn't choose one "best" type and reject the rest. It builds a union such asstring | number | null.
Functions with several return paths infer a union as well:
function parse(input: string) {
if (input === "") {
return null;
}
return Number(input);
}
// return type inferred as number | nullCallers of parse must now handle null before using the result. The compiler enforces this because the type says so.
Declared type versus narrowed type
When you annotate a variable with a union, the declared type stays the union. The compiler narrows what it knows at each point based on assignments.
let id: number | string = 1;
id.toFixed(1); // ok: after assigning 1, id is a number here
id = "abc";
id.toUpperCase(); // ok: now id is a string hereThis surprises people who expect the declaration to restrict the variable to number. The declared type limits what you can assign. The narrowed type limits what you can do at a given line. Narrowing has its own chapter later.
Variables with no initializer
If a variable has no initial value, the compiler has nothing to infer from at the declaration. Under noImplicitAny, TypeScript tracks the type through your assignments instead:
let value; // no type yet
value = 5;
console.log(value.toFixed(1)); // value is number here
value = "five";
console.log(value.toUpperCase()); // value is string hereThe same applies to an empty array literal:
const names = []; // starts as an "evolving" any[]
names.push("Ada");
names.push("Grace");
// names is now string[]This works, but it breaks easily. If you read the variable before the compiler can determine its type, or capture it in a nested function, you get an error such as Variable 'names' implicitly has type 'any[]' in some locations where its type cannot be determined. The fix is to annotate:
const names: string[] = [];Annotate empty arrays and uninitialized variables. It costs a few characters and avoids confusing errors.
How the compiler decides
An annotation always wins over inference. If you write const n: number = 5, then n is number, not 5.
When to annotate
Inference isn't always the better choice. A useful rule is to let the compiler infer values it can see and annotate the places where types act as a contract.
| Situation | Recommendation | Reason | Column |
|---|---|---|---|
| Local variable with an initializer | Infer | The annotation would only repeat the value. | |
| Function parameter | Always annotate | The compiler can't infer it, except from defaults or contextual typing. | |
| Exported function return type | Annotate | The signature stays stable and body mistakes surface where they occur. | |
| Internal helper return type | Usually infer | The body is nearby and the type is obvious. | |
| Empty array or `let` with no value | Annotate | Avoids evolving types and their errors. | |
| Value that should be wider than its initializer | Annotate | `let status: "idle" \ | "busy" = "idle"` states the intended set. |
The return type rule deserves an example. An inferred return type reflects what your code does, including any bug. An annotated return type reflects what you meant.
function average(values: number[]) {
if (values.length === 0) {
return undefined; // inferred: number | undefined
}
return values.reduce((a, b) => a + b, 0) / values.length;
}Here the inference is correct, but a caller might not expect undefined. Adding : number would make the compiler flag the early return and force you to decide whether to throw, return 0, or change the signature to number | undefined.
Checking what the compiler inferred
You don't have to guess. Hover over a name in an editor, or ask the compiler directly.
const point = { x: 1, y: 2 };
type Point = typeof point;
// Hover over Point to see: { x: number; y: number }typeof point in a type position gives you the inferred type, so you can reuse it. This works well for config objects, where you want a type without writing it twice.
Common mistakes
- Expecting
let x = nullto be flexible. UnderstrictNullChecks,let x = nullgivesxthe typenull, so you can't assign a number later. Writelet x: number | null = null. - Relying on inference for an exported API. A small change in the function body can silently change the return type that other modules see.
- Treating
constobjects as deeply constant. Properties still widen, souser.id = "x"is an error butuser.id = 2is allowed. - Leaving out parameter types and silencing the error with
any. This disables checking for every caller. Write the real type instead.
Summary of the working model
The compiler reads the initializer, return statements, default values, and surrounding context to produce a type. It widens or narrows that type according to const, let, and later assignments. It stops when there is nothing to read, which happens with parameters, empty containers, and uninitialized variables. Those are the places where you write the annotation.
Exercise
Without running it, what types does TypeScript infer for a, b, and the return type of pick? Explain why.
const a = [1, "x"];
const b = { n: 1 };
function pick(flag: boolean) {
if (flag) {
return b.n;
}
return "none";
}
Show answer
a is (string | number)[], because array elements combine into a union. b is { n: number }, because object properties widen even under const. The return type of pick is number | string, the union of the types in the two return statements. The return of b.n has type number, and "none" contributes string because the return type widens a literal for a function result.
Exercise
A teammate writes const results = []; at the top of a function, pushes strings into it inside a callback, and then gets an error about an implicit any[]. What is the cause, and what is the fix?
Show answer
An empty array literal has an evolving type that the compiler tracks through assignments in the same scope. Pushes inside a nested callback can't be tracked that way, so the type can't be determined. The fix is to annotate the array: const results: string[] = [];.