Functions with Types
Promise what goes into a function, and what comes back out.
1function add(a: number, b: number): number {
2 return a + b;
3}
4
5console.log(add(2, 3));
6console.log(add(10, 20));
$ npx tsc main.ts
$ node main.js
5
30
Every line, explained
function add(a: number, b: number): number {- Each parameter gets its own type (a: number), and the : number AFTER the round brackets is the return type: the kind of value the function promises to hand back. Call add("2", 3) and TypeScript stops you: wrong kind of input! The mistake would be caught while compiling, BEFORE the program ever runs. That is TypeScript's whole superpower.
return a + b;- Because both inputs are guaranteed to be numbers, a + b is guaranteed to be addition, never accidental text-gluing like "2" + 3 in plain JavaScript.
}- This } closes the function.
console.log(add(2, 3));- add(2, 3) passes the type check and becomes 5.
console.log(add(10, 20));- Same function, different (correctly typed) inputs: 30.