Function types
| Annotate signatures | |
| Type the whole function | |
| void returns | |
| never returns |
Annotate signatures
A signature is the list of parameter types plus the return type. Writing them down turns the function header into documentation that the compiler checks on every call. Start here whenever a function accepts input or produces output.
function add(a: number, b: number): number {
return a + b;
}
const total: number = add(2, 3);
Type the whole function
Sometimes the variable needs the type, not the function itself. A function type describes the full shape with an arrow between the parameter list and the return type. Assign any matching function and the variable keeps the same contract.
type Greet = (name: string) => string;
const greet: Greet = (name) => {
return "Hello, " + name;
};
void returns
Use void when the function returns nothing useful and only performs an action. Logging, saving, and alerting are classic void functions. Callers know there is no value to read, so they never use the result by mistake.
function log(message: string): void {
console.log(message);
}
log("Done");
never returns
Use never when the function cannot return at all because it always throws or loops forever. A helper that raises errors is the most common case. After calling it, TypeScript knows the code below is unreachable.
function fail(message: string): never {
throw new Error(message);
}
Next: Parameters
Article author: Arthur Isaev