1function area(w: number, h: number): number {function area(w: number, h = w): number {2 return w * h; return w * h + " cm";3}4const size = area(3, 4);const size = area(3);5console.log(size);tsctype checker!✓areareturns w * hw: number3h: numberh = w43?: number$ node area.js9area(w: number, h?: number): numberTS343129
Back row: area.ts (the code) and tsc, the type checkerFront row: the function as a machine (typed slots in, typed chute out) and the laptop that runs itTokens: argument values going into the slots, and the answer coming outAt the back: area.ts, the TypeScript you write, and tsc, the type checker. In front: the function area as a machine, with two typed input slots and a typed output, and a laptop running the program. Arguments fill the slots in order and tsc checks each one; the return type is checked on the return line. A wrong return and a missing argument are both caught before anything runs; the default h = w fills the empty slot, and the program prints 9. You can often leave the return type out: TypeScript infers it from the return lines. Writing it anyway makes the promise explicit, so a wrong return is reported inside the function instead of where the result is used.

Typed inputs and output

  1. A function is a small machine. Values go in, it does its work, and one value comes out. Typing a function means writing down which kinds of values may go in, and which kind comes out.

tsc checks every call

Default values

In your editor

What happens

;; step 1/9 · machine
area.ts
> 1  function area(w: number, h: number): number {
> 2      return w * h;
> 3  }
  4  const size = area(3, 4);
  5  console.log(size);

area takes a width w and a height h
and gives back w * h

You can often leave the return type out: TypeScript infers it from the return lines. Writing it anyway makes the promise explicit, so a wrong return is reported inside the function instead of where the result is used. tsc 5.9 with no settings writes older JavaScript: it turns const into var and h = w into an if statement. Settings such as target change those details; the types are always removed.