Functions
Annotate parameters and returns
Types on parameters are checked at every call. A return type documents the output.
function add(a: number, b: number): number {
return a + b;
}
console.log(add(2, 3));
Use optional and default params
Optional parameters may be omitted. Defaults provide a value when the argument is missing.
function greet(name: string, greeting = "Hello"): string {
return `${greeting}, ${name}`;
}
console.log(greet("World"));
console.log(greet("World", "Hi"));
Type arrow functions
The same annotations work on arrow functions and callbacks.
const double = (n: number): number => n * 2;
const nums = [1, 2, 3].map(double);
console.log(nums);
Void and never briefly
voidmeans the function does not return a useful valuenevermeans it never completes normally (throw or infinite loop)- Prefer explicit return types on public helpers
- Rest parameters use
...args: number[]
Comments
One comment per signed-in account. Comments are saved with this page’s URL.