Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 96 ยท Getting Started

Type Inference

Learn how TypeScript infers types from values and returns, how let and const widen literals, best common types, contextual typing, and when annotations help.

In the last lesson you annotated everything: let score: number = 0. In real TypeScript code you'll write far fewer annotations, because the compiler can usually work out the type itself. Write let score = 0, and TypeScript already knows score is a number. This is type inference, and it's one of the reasons TypeScript code often looks almost like plain JavaScript.

Inference isn't guessing. It follows precise rules, and knowing them lets you predict what type every variable gets. In this lesson you'll learn how types flow from values and return statements, why let and const produce different types, how arrays of mixed values are typed, how callbacks get their parameter types for free, and the simple rules professionals use for deciding when to annotate.

Inference from initial values

When you declare a variable with an initial value, the variable gets the type of that value:

TypeScript Types inferred from values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints OSLO 710000 true and 1048 2. There isn't a single annotation, yet the program is fully type-checked. TypeScript inferred:

Variable Inferred type
city string
population number
isCapital boolean
founded Date
tags string[]

These are exactly as strict as written annotations. Assigning city = 42 later fails with Type 'number' is not assignable to type 'string'. The type is fixed at the declaration; inference just saves you from writing it.

Seeing inferred types

In VS Code you hover over a name to see its type. Our editors have no hover, but there's a neat trick that works anywhere: assign the value to a variable of type never. Nothing can be assigned to never, so the compiler reports an error, and the error message names the type it inferred:

TypeScript Reveal inferred types (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The error list is really a list of types:

TEXT
main.ts(6,7): error TS2322: Type 'string' is not assignable to type 'never'.
main.ts(7,7): error TS2322: Type '"Norway"' is not assignable to type 'never'.
main.ts(8,7): error TS2322: Type '(string | number | null)[]' is not assignable to type 'never'.
main.ts(9,7): error TS2322: Type '{ x: number; y: number; label: string; }' is not assignable to type 'never'.

Two of these deserve a closer look. Why is country typed "Norway" and not string? And what is (string | number | null)[]? The next two sections explain.

let vs const: widening

A literal type is a type with exactly one value. "Norway" is the type whose only value is the string 'Norway', and 3.14 is the type whose only value is 3.14. You'll explore them fully in Literal Types and as const.

Which type a variable gets depends on whether it can change:

  • A const can never be reassigned, so TypeScript keeps the narrowest type: the literal itself. const country = 'Norway' has type "Norway".
  • A let can be reassigned later, so TypeScript widens the literal to its general type. let city = 'Oslo' has type string, because you'll probably want to store other cities in it.

This widening also applies to object properties and array elements, even inside a const. A const object can't be replaced, but its properties can still be changed, so they're widened too. That causes a classic surprise:

TypeScript A widened property (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The first call is fine, because 'dark' is a literal. The second fails:

TEXT
main.ts(8,10): error TS2345: Argument of type 'string' is not assignable to parameter of type '"dark" | "light"'.

The parameter type 'dark' | 'light' means "one of these two strings exactly" (a union type). settings.mode was inferred as string, since someone could later write settings.mode = 'purple'. TypeScript can't promise it's still 'dark'. There are three good fixes:

TypeScript
// 1. Annotate the object with the type you mean
const settings: { mode: 'dark' | 'light'; fontSize: number } = { mode: 'dark', fontSize: 14 };

// 2. Freeze the object's types with as const (all properties become readonly literals)
const settings = { mode: 'dark', fontSize: 14 } as const;

// 3. Annotate just the property's value
const settings = { mode: 'dark' as 'dark' | 'light', fontSize: 14 };

The first is the clearest in most code. The second is great for constant configuration tables. Try the first fix in the editor; the program then prints Theme set to dark twice.

Inferring function return types

TypeScript infers a function's return type from its return statements, so you can leave the return annotation out:

TypeScript Inferred return types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints 4.5, small large and { id: 1, name: 'Ada' } undefined. The inferred return types are:

  • half returns number.
  • sizeLabel returns "large" | "small": a union of the two literals it can return.
  • findUser returns { id: number; name: string; } | undefined: every return path counts, so the type honestly says "maybe nothing".

That last one is a big help. Because the return type includes undefined, the compiler will insist that callers check before using .name. You'll learn those checks in Narrowing.

Return types also widen when you store them in a let. let label = sizeLabel(3) gives label the type string, while const label = sizeLabel(3) keeps "large" | "small".

Best common type

When TypeScript infers an array type from several elements, it looks for a type that fits all of them. If they share one type, that's it: [1, 2, 3] is number[]. If they don't, the result is a union of the element types: [1, 'two', null] is (string | number | null)[], an array whose elements may each be a string, a number or null.

TypeScript Arrays of mixed values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output is total 252, then string Ada, number 36, boolean true, then [ 9.99, 4.5 ]. Inside the loop, cell has type string | number | boolean, so you'd need a typeof check before calling string or number methods on it.

If the array is supposed to hold a fixed sequence of specific types, like "a name, then an age", inference can't know that. You say so with a tuple type such as [string, number], covered in Arrays and Tuples.

Empty arrays

An empty array gives inference nothing to work with. In strict mode, TypeScript lets an array declared as const items = [] "evolve" as you push values into it, but the resulting type is easy to get wrong and harder to read. Annotate empty arrays instead:

TypeScript
const names: string[] = [];
names.push('Ada');     // fine
names.push(42);        // error: number is not assignable to string

Contextual typing

Inference also works in the other direction. Sometimes the place where a value appears determines its type. This is called contextual typing, and you rely on it every time you pass a callback:

TypeScript Callbacks typed by their context

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints [ '$12.50', '$8.00', '$30.00' ], [ 12.5, 30 ] and 2.5 KG. Notice that price, p, value and unit have no annotations, and yet this compiles in strict mode:

  • prices is a number[], so the callback passed to map must accept a number. TypeScript gives price the type number from that context.
  • labels is inferred as string[], because the callback returns a string.
  • formatWeight is declared with the function type Formatter, so its parameters get number and string from the type. You'll meet function types like this in Function Types and Callbacks.

Contextual typing only works when the context exists. A standalone function such as function format(value) { ... } has no context, so value gets no type, and strict mode reports TS7006: Parameter 'value' implicitly has an 'any' type.

When should you annotate?

With inference this capable, the question becomes when to write types at all. Most teams follow rules close to these:

Write an annotation Let TypeScript infer
Function parameters (always; there's no context to infer from) Variables with an initial value: let count = 0
A variable declared without a value: let total: number; Callback parameters passed to map, filter, event handlers and so on
Empty arrays and objects that you fill later Local results like const labels = prices.map(...)
When inference picks a wider type than you mean (mode: 'dark' | 'light') Return types of small, private helper functions
Return types of exported or public functions, so the contract is explicit Anything where the annotation would just repeat the obvious

The return-type rule deserves a word. Inferred return types are always correct, but they describe what the code does, not what you meant. An explicit return type turns a mistake inside the function into an error right there, instead of an error in some distant caller:

TypeScript An explicit return type catches the mistake early (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The error points straight at the typo:

TEXT
main.ts(8,18): error TS2561: Object literal may only specify known properties, but 'precent' does not exist in type 'Discount'. Did you mean to write 'percent'?

Without the : Discount annotation, the function would compile and return { code: string; precent: number }, and the problem would appear wherever the result was used. Fix the spelling and it prints { code: 'SPRING15', percent: 15 }.

Good TypeScript has types at the edges. Annotate where data enters and leaves a function or module (parameters, exported return types, empty containers) and let inference handle everything in between. Code stays short, and every important contract is still written down.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the type of level in const level = 'beginner';?

    A const can never be reassigned, so TypeScript keeps the literal type "beginner" instead of widening it to string.
  2. 2. What is the type of items in const items = ['pen', 4, 'ink'];?

    The best common type of the elements is the union string | number, so the array is (string | number)[]. A tuple is only inferred when you ask for one.
  3. 3. const config = { env: 'prod' }; and function deploy(env: 'dev' | 'prod') {}. Does deploy(config.env) compile?

    Object properties can be changed even in a const object, so their literal types are widened. Annotate the object or use as const to keep the literal.
  4. 4. In [1, 2, 3].map((n) => n * 2), how does TypeScript know that n is a number?

    The callback's position gives it its type. Because the array is number[], map's callback parameter is a number.
  5. 5. Which of these is the best place to add an explicit annotation?

    Parameters have no context to infer from, and exported functions are contracts other code depends on. The other three are inferred correctly.

Summary

  • Type inference gives variables the type of their initial value and functions the type of their return statements. Inferred types are just as strict as annotations.
  • To see an inferred type without an editor, assign the value to a never variable and read the error message.
  • const keeps literal types ("Norway"); let, object properties and array elements widen to the general type (string). Fix unwanted widening with an annotation or as const.
  • Functions with several returns get a union return type, including undefined when a path returns nothing.
  • Mixed arrays get the best common type, often a union such as (string | number)[]. Annotate empty arrays.
  • Contextual typing types callback parameters from where the callback is used.
  • Annotate parameters, uninitialized variables, empty containers and exported return types; let inference handle the rest.

Next: The tsconfig.json File โ€” the compiler options that shape how strict and how modern your project is.