Skip to the content.

Chapter 2: How TypeScript Infers Types

Runnable examples: examples/ch02-inference.ts

Most types in good TypeScript code are never written down; they are inferred. Knowing the inference rules tells you when to annotate and when to stay out of the way.

Widening: why let and const differ

let mutableColor = "red";  // string
const fixedColor = "red";  // "red"

A const can never change, so TypeScript keeps the precise literal type. A let can be reassigned, so its literal type is widened to string. The same logic applies to object properties, which are mutable:

const config = { mode: "dark", retries: 3 };
// { mode: string; retries: number }

This is the source of the classic error where a function expects "dark" | "light" and you pass config.mode, which is string.

as const: freeze the literal

as const creates a const context: no widening, and everything becomes readonly, recursively.

const frozen = { mode: "dark", retries: 3, tags: ["a", "b"] } as const;
// { readonly mode: "dark"; readonly retries: 3; readonly tags: readonly ["a", "b"] }

Its most useful trick: derive a union type from a runtime list, so you have one source of truth.

const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number]; // "admin" | "editor" | "viewer"

Combine it with a type guard (isRole) to safely turn untrusted strings into Role.

Best common type

For array literals, TypeScript computes a type that fits all elements:

const mixed = [1, "two", null]; // (string | number | null)[]

Notice it is an array of a union, not a tuple. If you want a tuple, annotate it or use as const.

Contextual typing: inference that flows backwards

Usually types flow from values to variables. Contextual typing flows the other way: from the expected type into an expression.

["a", "bb"].map((s) => s.length); // s: string, from Array<string>.map's signature

type Handler = (event: { type: "click"; x: number }) => void;
const onClick: Handler = (event) => event.x; // event typed from Handler

This is why callbacks rarely need annotations, and why extracting a callback into a standalone const sometimes suddenly requires one: the context is gone.

Return type inference

function parsePort(input: string) {
  const n = Number(input);
  if (Number.isInteger(n) && n > 0 && n < 65536) return n;
  return null;
}
// ReturnType<typeof parsePort> is number | null

Inferred return types are convenient, but for exported functions consider writing the return type explicitly. It documents the contract, catches accidental changes (returning undefined from a new branch), and speeds up type checking in large projects.

satisfies: check without losing precision

Annotations replace the inferred type with the annotated one. satisfies (TypeScript 4.9+) checks the value against a type but keeps the inferred type.

type ColorValue = `#${string}` | [number, number, number];
type Theme = Record<string, ColorValue>;

const theme = {
  primary: "#3355ff",
  background: [255, 255, 255],
} satisfies Theme;

theme.primary.toUpperCase(); // OK: TypeScript knows primary is a string
theme.background[0];         // OK: a tuple element

With const theme: Theme = ..., every property would have type ColorValue, and theme.primary.toUpperCase() would fail because the value might be a tuple. Also, keyof typeof theme would be string instead of "primary" | "background".

When to use which

Goal Use
Value must conform, and you want its exact shape afterwards satisfies
Variable will be reassigned with other values of the type annotation
Literal values must not widen, and the object is read-only as const
Both conformance and literal precision as const satisfies T
You know better than the compiler (rare) as, with care (Chapter 10)

Check yourself

  1. Why does const c = { mode: "dark" }; setMode(c.mode) fail when setMode takes "dark" | "light"? Give two fixes.
  2. What is the type of ["x", 1] as const?
  3. Why might extracting an inline callback into a variable produce an implicit any error?
Answers 1. The property widens to `string`. Fix with `as const`, or annotate `c` with a type whose `mode` is the union. 2. `readonly ["x", 1]`. 3. The callback loses its contextual type, so its parameters have nothing to be inferred from.

Next: Chapter 3, Narrowing and Control Flow