Hone

Lessons · TypeScript · type annotations

Saying what a thing is

name: type after a parameter or variable tells the compiler what it holds; the compiler then refuses anything else before the code runs.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Most bugs in untyped code are a value of the wrong shape arriving somewhere. Annotations catch them at the boundary, in the editor, not in production.

How to think about it

What must this be? Annotate function parameters and return types always; let the compiler infer local variables. Read an annotation as 'must be a'.

Worked example

function area(w: number, h: number): number {
Two numbers in, a number out.
  return w * h;
A number, as promised.
}
area("3", 4)
Error: string is not assignable to number. Caught before running.

Your turn

Type the parameter and the return.

function shout(s: ): string {
  return s.toUpperCase();
}

The trap

Annotating everything, including const x: number = 5. The compiler already knows; extra annotations are noise.

Practise type annotations on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.