Sub topic 3
How TypeScript Infers Types
This chapter assumes you know basic TypeScript annotations such as let n: number, that you can run code with tsc or an editor with TypeScript support, and that you understand the strict compiler option. Inference is the compiler's way of working out a type without you writing it. Knowing what it infers lets you decide where an annotation adds value.
Where inference applies
TypeScript infers types from the initial value of a variable, from the return statements of a function, and from the context a callback is passed into. It does not infer parameter types from their use inside the function body. Parameters need an annotation, or a contextual type, or a default value.
let count = 0; // number
const label = "Ada"; // "Ada" (literal type)
let items = [1, 2, 3]; // number[]
function add(a: number, b: number) {
return a + b; // return type inferred as number
}
const doubled = [1, 2, 3].map((n) => n * 2); // n is numberconst versus let
A const declaration keeps the narrowest type of its value. A let declaration widens a literal to its primitive type, because the variable can be reassigned later.
const status = "ok"; // type "ok"
let mode = status; // widened to string
mode = "error"; // allowedObject literals widen in the same way. Each property of { mode: "dev" } gets the type string, not "dev". The as const assertion, covered later in this series, prevents that widening.
Mixed arrays
An array literal infers the union of its element types. [1, "a"] has the type (string | number)[]. That is often not what you want, so check the inferred type when a later call fails.
Diagnosing inferred types
Hover over a name in your editor to see its type. You can also force a check with a deliberate assignment:
const pair = [1, "a"];
const check: never = pair; // error message shows the inferred typeThe error text names the inferred type, so you can read it without guessing.
Exercise
Exercise
What type does TypeScript infer for flag in let flag = true; and for flag2 in const flag2 = true;?
Show answer
flag is boolean because let widens the literal. flag2 is the literal type true because const keeps it.