← TypeScript

Basic · 2 of 13 · 12 min read

Annotations and inference

Where to write a type and where to let the compiler work it out, why let widens and const does not, and what contextual typing gives you for free.

  • Type annotations
  • Type inference

An annotation states a type. Inference works one out. A well-typed codebase has far fewer annotations than people expect, because the compiler is good at the second one — and the skill is knowing the few places where stating it beats inferring it.

The syntax

let count: number = 0;
const names: string[] = ["Ana"];

function greet(name: string): string {
  return `Hi ${name}`;
}

const double = (n: number): number => n * 2;

interface User {
  id: number;
  name?: string; // optional
}

An annotation is a contract for the whole life of the binding, not just the first assignment:

let count: number = 0;
// count = "three"; // Type 'string' is not assignable to type 'number'

Inference is the default

Leave the annotation off and the compiler works it out from the initialiser:

let count = 0;              // number
const names = ["Ana"];      // string[]
const user = { id: 1 };     // { id: number }

function greet(name: string) {
  return `Hi ${name}`;      // the return type is inferred as string
}

// And the inferred types are enforced exactly like written ones:
// count = "three";          // not assignable
// names.push(42);           // not assignable

So const name: string = "Ana" is three words longer than const name = "Ana" and no safer. The annotation earns its place when it changes something.

Widening: let versus const

let a = "hello";    // string
const b = "hello";  // "hello" — the literal type

A let can be reassigned, so the compiler widens the literal to its general type. A const can never change, so it keeps the exact value as its type. That matters the moment a literal union is involved:

type Method = "GET" | "POST";

const good = "GET";
let loose = "GET";

function call(method: Method) {}

call(good);              // fine — good is "GET"
// call(loose);          // 'string' is not assignable to 'Method'
call(loose as Method);   // or: let loose: Method = "GET"

Object properties widen for the same reason — they are mutable:

const config = { method: "GET" };  // method: string, not "GET"

// call(config.method);            // not assignable

const frozen = { method: "GET" } as const; // method: "GET"
call(frozen.method);                        // fine
Declaration Inferred type
let x = "a" string
const x = "a" "a"
const o = { x: "a" } { x: string }
const o = { x: "a" } as const { readonly x: "a" }
let x = [1, 2] number[]
const x = [1, 2] as const readonly [1, 2]

Contextual typing

The position a function appears in supplies its parameter types, so a callback almost never needs annotations:

const names = ["Ana", "Beto"];

names.forEach((name) => console.log(name.toUpperCase())); // name: string

type Handler = (event: { id: number }) => void;
const onEvent: Handler = (event) => console.log(event.id); // event is typed

// Out of position there is nothing to infer from:
// const loose = (name) => name; // Parameter 'name' implicitly has an 'any' type

This is what noImplicitAny is about: not the word any, but the positions where the compiler cannot infer and would otherwise fall back to no checking at all.

// Rejected under noImplicitAny — nothing to infer from:
// function double(n) { return n * 2; }

function double(n: number) { return n * 2; }  // annotate the parameter
const explicit: any = 1;                       // an explicit any is still allowed

Where an annotation earns its place

On parameters. There is nothing to infer from, so this is not optional.

On a return type, to move the error. Without one, a body that returns the wrong thing changes the inferred type and the failure appears at the caller. With one, it is reported in the function.

function inferred(id: number) {
  return id.toString();          // inferred: string
}

function annotated(id: number): number {
  // return id.toString();       // Error reported HERE
  return id;
}

const a: number = annotated(1);
// const b: number = inferred(1); // the error lands at the call site instead

On an empty collection, which has nothing to infer from:

const items: string[] = [];
items.push("a");
// items.push(1); // caught

const loose = [];   // implicitly any[] — "evolving", and never checked
loose.push("a");
loose.push(1);      // no complaint

On an exported value, so a change inside the module is a decision rather than an accident:

export const DEFAULTS: { retries: number; debug: boolean } = {
  retries: 3,
  debug: false,
};
// Removing `debug` is now an error here, not a surprise for every importer.

Deriving instead of repeating

When a type already exists somewhere, typeof lifts it rather than restating it:

const defaults = { retries: 3, timeout: 5000 };

type Config = typeof defaults;        // { retries: number; timeout: number }
type Key = keyof typeof defaults;     // "retries" | "timeout"

function configure(options: Config) { return options.retries; }
console.log(configure({ retries: 5, timeout: 1000 })); // 5

Two typeofs share the keyword: in an expression it is JavaScript’s runtime operator returning a string, and in a type position it is TypeScript’s type query. Context tells them apart.

Common mistakes

Annotating what was already inferred

Mistake. const names: string[] = ["Ana"] and a return type on every private helper. Why it fails. It is not wrong, just noise — one more thing to update, with no extra checking. What to do instead. Annotate boundaries and empty collections; let inference do the middle.

Expecting a let to keep its literal type

Mistake. let method = "GET" passed to something expecting "GET" | "POST". Why it fails. The compiler widened it to string, because a let can be reassigned. What to do instead. const, an explicit annotation, or as const on an object.

Reading noImplicitAny as “no any”

Mistake. Thinking the flag bans the keyword. Why it fails. It targets positions the compiler cannot infer. An any you wrote deliberately is still allowed — the flag is about accidents. What to do instead. Annotate the parameter. If you genuinely want no checking, write any and say why in a comment.

Check yourself

4 questions from the bank on what you just read. Answering here does not affect your quiz history.

An annotation describes what a value is allowed to be, and the compiler holds you to it.

Why does the second line fail to compile?

Code sample
let count: number = 0;
count = "three";

When is an explicit return-type annotation on a function worth writing?

The compiler widens a let so it can be reassigned, and keeps a const exact.

What types are inferred for a and b?

Code sample
let a = "hello";
const b = "hello";

What does noImplicitAny actually stop you from doing?

Practise Type annotations and Type inference →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.