Type annotations and type inference

Beginner · 8 min

How TypeScript works out most types from your values, where you still need to write an annotation, and why fewer annotations is usually better.

Before thisPrimitive types

Code Ryan · 8 min

Type annotations and type inference

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Code RyanReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A type annotation is a `: Type` written after a name; it states what the name may hold, and the compiler checks every assignment against it.
  • When a variable has an initializer, TypeScript infers its type from that value, so `let count = 0` is already a `number` with no annotation.
  • Inferred types are just as strict as annotated ones; inference saves typing, it does not loosen the check.
  • `let` infers a widened type such as `string`, while `const` keeps the exact literal such as `"ready"`, because a `const` can never be reassigned.
  • Write annotations where there is nothing to infer from (a variable declared without a value, a function parameter) or where you want to state a contract the value must meet; elsewhere, let inference work.

Annotating everything would be miserable

The previous lesson wrote types on every variable:

let title: string = "Dune";

That line says the same thing twice. The value "Dune" is plainly a string; the annotation adds nothing the compiler could not see for itself. If TypeScript required this everywhere, a typed codebase would be half annotations, and every change of type would mean editing two places. So it doesn’t require it. Most of the time, the compiler works the type out from the value. That is type inference, and understanding where it applies tells you where annotations are actually needed.

The annotation: a promise the compiler holds you to

An annotation is a colon and a type after a name:

let price: number = 19.99;
price = 24.5; // fine
price = "free"; // Error: Type 'string' is not assignable to type 'number'.

Every later assignment is checked against it. The annotation is a contract, and the compiler is the party that enforces it.

Inference: the same contract, written for you

Remove the annotation and nothing about the checking changes:

let count = 0; // inferred: number
count = 1; // fine
count = "zero"; // Error: Type 'string' is not assignable to type 'number'.

TypeScript looked at the initializer, saw a number, and fixed the variable’s type to number for good. Hover over count in your editor and it shows let count: number. This is the first thing to internalize: an inferred type is not a weaker or provisional type. It is enforced exactly like one you wrote.

Inference reaches further than simple variables. Arrays, objects, and expressions all get types:

const tags = ["ts", "types"]; // string[]
const book = { title: "Dune", pages: 412 }; // { title: string; pages: number }
const half = book.pages / 2; // number
const loud = book.title.toUpperCase(); // string

None of these lines carries an annotation, and every one of them is fully typed. Return types of functions are inferred the same way, which the typing functions group picks up.

let widens, const does not

There is one twist in what gets inferred:

let mode = "light"; // string
const theme = "light"; // "light"

A let can be reassigned, so if TypeScript inferred the exact value "light", you could never set it to "dark". It widens the type to string. A const can never change, so the compiler keeps the precise type: the literal "light", a type with exactly one member. Literal types turn out to be very useful, and the union and literal types lesson builds on them. For now, just expect the hover to show different things for let and const.

Where you still need an annotation

Inference needs something to infer from. When there is nothing, you write the type.

A variable declared without a value. If the value arrives later, say in a branch, state the type up front so each assignment is checked against your intent:

let label: string;

if (Math.random() > 0.5) {
  label = "heads";
} else {
  label = 42; // Error: Type 'number' is not assignable to type 'string'.
}

Function parameters. A parameter has no value until a caller supplies one, so a standalone function needs its parameters annotated. The parameter and return types lesson covers why.

A value whose first assignment is narrower than its job. If a variable starts as null and later holds a user name, inference from null alone would get it wrong:

let currentUser: string | null = null;
currentUser = "ada"; // fine, because the annotation allowed both

A contract you want checked at the source. Annotating an object literal with a named type reports a typo in that literal, at that line, instead of three files away where the object is finally used. That is a deliberate use of annotation as documentation the compiler verifies.

A working rule

Think of annotations like labels on circuit breakers. You label the ones whose purpose is not obvious from the wiring; you do not label a lamp cord “lamp cord”. In TypeScript terms: annotate parameters, uninitialized variables, and public boundaries such as exported values. Let inference handle local variables with obvious initializers. If you are unsure what got inferred, hover over the name; the editor always tells you, and the editor lesson shows how much more it can tell you.

The opposite mistake also exists: annotating a const with a wider type than its value throws information away. const theme: string = "light" loses the literal type that inference would have given you for free.

About the video

Code Ryan’s video is a focused walk through inference: what TypeScript works out from initializers, how arrays and objects get inferred types, and the cases where leaving the annotation off is the better choice. It is a 2022 recording, and nothing it shows has changed in TypeScript 5. The written lesson adds the let versus const widening rule and the specific situations where an annotation is required rather than optional. Benny Code’s shorter video in the links is a compact second take on the same contrast.

Check yourself

  1. 01Is `let count = 0; count = "zero";` an error, given that `count` has no annotation?

    Yes. TypeScript inferred `number` from the initializer `0`, and the inferred type is enforced exactly like a written one. The second line fails with "Type 'string' is not assignable to type 'number'".

  2. 02Why does `let status = "ready"` have type `string` while `const status = "ready"` has type `"ready"`?

    A `let` can be reassigned later, so inferring the single literal `"ready"` would forbid every other string; TypeScript widens it to `string`. A `const` can never change, so the narrower literal type is both safe and more precise.

  3. 03When should you annotate a variable that TypeScript could already infer?

    When the annotation states a requirement rather than repeating the value, such as giving a variable a wider type than its first value (`let total: number | null = null`), or checking that an object literal matches a named type so mistakes are reported at the literal instead of wherever it is used later.

  4. 04What goes wrong with `let result;` followed by assignments in several branches?

    The declaration has nothing to infer from, so the variable's type is pieced together from later assignments and can end up wider than you meant, or `any` in some positions. Annotating it, as in `let result: string;`, makes the compiler check each assignment against your intent.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark