Functions
9 min · TypeScript
Package code under a name, with typed inputs and outputs.
Enemy 1 of 5
A function names a reusable block of code — write it once, then call it wherever it's needed. Defining a function doesn't run it; it only runs when called by name with parentheses, e.g. double(5).
In TypeScript you can type each parameter and the return value: function double(n: number): number means double takes one argument, n, which must be a number, and promises to return a number back. This is one of the biggest practical wins TypeScript offers — if double("5") is ever called by mistake somewhere in a large codebase, TypeScript flags it immediately rather than letting the mistake ship and fail at runtime, possibly far from where the bug actually originated.
Use return to hand a value back to whoever called the function. If the function's return type is declared as number but a code path inside it tries to return a string instead, TypeScript will refuse to compile until that's fixed.
Loading editor...