Type annotations and inference

Topic 1 of 4 in Everyday types7 min readIntermediateFree course

Overview

You can annotate every variable in a TypeScript program, but you shouldn’t. TypeScript is very good at working out types by itself — inference — and code full of redundant annotations is harder to read. The skill is knowing where an annotation adds information and where it just repeats what the code already says.

Annotations

An annotation is a colon and a type:

TypeScript
let city: string = "Pune";
const year: number = 2026;

function shout(text: string): string {
  return text.toUpperCase() + "!";
}

Once something has a type, TypeScript checks every value that goes into it:

TypeScript
city = 42;
// error TS2322: Type 'number' is not assignable to type 'string'.

Inference

Delete the annotations and hover over the names in your editor — the types are the same:

TypeScript
let city = "Pune";          // let city: string
const year = 2026;          // const year: 2026  (more on this below)
const scores = [91, 78];    // const scores: number[]
const user = { name: "Asha", age: 29 };   // { name: string; age: number }

TypeScript infers types from values. let drink = “tea” is inferred as string — let can change, so the type widens. const size = “large” is inferred as the literal type “large” — const never changes. const prices = [3.5, 4] becomes number[], an array of the element type. const user = { name: “Asha”, age: 29 } becomes { name: string; age: number }. function double(n: number) { return n * 2; } returns number — the return type is inferred. Rule of thumb: annotate function parameters (TypeScript can’t guess them); let it infer the rest.

Inference isn’t guessing: the checker knows exactly what type every expression produces, and flows that information forward. Inferred types are checked just as strictly as annotated ones — city = 42 is still an error.

Return types are inferred too

TypeScript
function double(n: number) {
  return n * 2;            // function double(n: number): number
}

Where annotations are needed

Function parameters

TypeScript can’t know what callers will pass, so parameters without an annotation are an error in strict mode:

TypeScript
function applyDiscount(price, percent) { … }
// error TS7006: Parameter 'price' implicitly has an 'any' type.

Always annotate parameters. (The exception: callbacks, below.)

Variables that start empty

TypeScript
let best;                       // no value to infer from yet
let best: string | undefined;   // better: say what it will hold

A variable declared without a value has nothing to infer from. TypeScript doesn’t report an error — it lets the type “evolve” with each assignment — but the result is hard to read and easy to get wrong: hovering shows a different type on different lines. Give such variables a type up front, here “a string, or undefined until we find one” (| makes a union, covered in Union and literal types).

The same goes for empty arrays you fill later: const names: string[] = [];.

When you want to state an intention

Sometimes an annotation is a promise you want checked:

TypeScript
function cartTotal(items: Item[]): number {
  …   // if a code path forgets to return a number, the error is HERE,
}     // not in the 20 places that call cartTotal

Return-type annotations are a good habit on exported functions and anything other code depends on: they document the contract and keep mistakes close to their cause.

Literal types and widening

Hover over these two:

TypeScript
let mode = "fast";     // let mode: string
const level = "fast";  // const level: "fast"

"fast" here is a literal type: a type that contains exactly one value. A const can never change, so TypeScript gives it the most precise type possible. A let might be reassigned to any other string later, so TypeScript widens the type to string.

Numbers and booleans work the same way: const max = 10 has type 10; let max = 10 has type number. Literal types become very useful with unions — "sm" | "md" | "lg" — and with as const (as const and satisfies).

Contextual typing

Inference also works backwards: when a function’s type is known, TypeScript types the callback parameters for you:

TypeScript
const names = ["asha", "ben"];
names.map((name) => name.toUpperCase());
//         ^? name: string — from the array's type

window.addEventListener("keydown", (event) => event.key);
//                                  ^? event: KeyboardEvent

That’s why you rarely annotate callback parameters.

Annotations vs assertions

An annotation asks TypeScript to check a value. A type assertion (as) tells TypeScript to trust you:

TypeScript
const a: number = JSON.parse("42");     // checked against number… but JSON.parse returns any
const b = JSON.parse("42") as number;   // "trust me"

Assertions don’t change the value or check anything at run time; if you’re wrong, the bug just moves elsewhere. Use them only when you genuinely know more than the checker — and prefer validating the data (Validating external data).

A practical style

  • Parameters: always annotate.
  • Return types: annotate on exported and important functions; let small helpers infer.
  • Variables: let TypeScript infer, except when they start empty or you want to enforce a wider/narrower type.
  • Callbacks: let context type them.
  • When unsure: hover. If the inferred type is what you meant, you don’t need the annotation.

The goal: types where they carry information, inference everywhere else. Your code should look like JavaScript with a few well-placed labels.

Exercise

Annotate only what’s needed

The starter has too many annotations in some places and too few in others. (1) Remove every annotation TypeScript can infer by itself. (2) Add the annotations that are missing: the parameters of applyDiscount, its return type, and best, which starts as undefined but later holds a string. (3) Hover over mode and level in your editor and explain in a comment why one is string and the other is "fast". The program should print Best deal: Laptop at 899.10 then fast fast.

TypeScript
const shop: string = "Corner Tech";
const prices: number[] = [999, 49.5, 12];
const names: string[] = ["Laptop", "Mouse", "Cable"];

function applyDiscount(price, percent) {
  return price * (1 - percent / 100);
}

let best;
let bestPrice: number = 0;
for (let i: number = 0; i < prices.length; i++) {
  const discounted: number = applyDiscount(prices[i] ?? 0, 10);
  if (discounted > bestPrice) {
    bestPrice = discounted;
    best = names[i];
  }
}
console.log(`Best deal: ${best} at ${bestPrice.toFixed(2)}`);

let mode = "fast";
const level = "fast";
console.log(mode, level);

Summary

  • An annotation is : Type after a variable, parameter or before a function body; TypeScript checks every value against it.
  • TypeScript infers types from initial values, return statements and context — most variables need no annotation.
  • Always annotate function parameters; annotate return types on exported or important functions.
  • let x = "a" widens to string; const x = "a" keeps the literal type "a".
  • Annotate variables that start empty (let best: string | undefined) or when you want the checker to enforce a type you have in mind.