Function types
Overview
Functions are the heart of JavaScript, and typing them well is where TypeScript pays off most: every call is checked against the function’s parameters, and every caller knows exactly what comes back. This lesson covers function syntax, function types (types that describe functions), and callbacks.
Parameters and return types
function total(prices: number[], tax = 0.2): number {
return prices.reduce((sum, p) => sum + p, 0) * (1 + tax);
}- Parameter types come after each name. They’re required (strict mode won’t let parameters be implicitly
any). - A default value makes a parameter optional and gives TypeScript its type:
taxis anumber. - The return type comes after the parameter list. It’s inferred if you leave it out, but writing it documents the function and makes TypeScript report a wrong
returninside the function rather than at every call site.
Calls are checked against all of it:
total([10, 20]); // ✓ tax defaults to 0.2
total([10, 20], 0.05); // ✓
total(10);
// error TS2345: Argument of type 'number' is not assignable to parameter of type 'number[]'.
total([10], 0.05, true);
// error TS2554: Expected 1-2 arguments, but got 3.Arrow functions and function expressions
Exactly the same annotations:
const double = (n: number): number => n * 2;
const greet = function (name: string): string {
return `Hi ${name}`;
};Function types
A function type describes the shape of a function — its parameters and return type — without a body:
type Formatter = (value: number) => string;
const asPrice: Formatter = (value) => `$${value.toFixed(2)}`;
const asPercent: Formatter = (value) => `${Math.round(value * 100)}%`;Note that inside asPrice, value needs no annotation: TypeScript takes it from Formatter. And the parameter names in a function type are only documentation — (n: number) => string is the same type.
A function with fewer parameters fits a function type with more — just like JavaScript lets you ignore extra arguments:
const alwaysZero: Formatter = () => "0"; // ✓ fine to ignore `value`Function types can also be written as a method or call signature inside an object type:
type Calculator = {
add(a: number, b: number): number;
subtract: (a: number, b: number) => number;
};Callbacks
Most of the time you don’t write function types for callbacks — the function you pass them to already has one, so the parameters are typed from context:
const names = ["asha", "ben"];
names.map((name, index) => `${index + 1}. ${name}`);
// ^? name: string, index: number
setTimeout(() => console.log("done"), 1000);
button.addEventListener("click", (event) => {
event.clientX; // event: MouseEvent
});When you write a function that takes a callback, you write the type:
function retry(times: number, action: () => boolean): boolean {
for (let i = 0; i < times; i++) {
if (action()) return true;
}
return false;
}
retry(3, () => Math.random() > 0.5);void callbacks
() => void means “a function whose return value will be ignored”. TypeScript lets you pass functions that return something anyway, because nothing will use the value:
function onEach(items: string[], callback: (item: string) => void) {
for (const item of items) callback(item);
}
const seen: string[] = [];
onEach(["a", "b"], (item) => seen.push(item)); // ✓ push returns a number; ignoredFunctions that return functions
Functions are values, so they can create and return other functions. The return type is just a function type:
function multiplier(factor: number): (n: number) => number {
return (n) => n * factor;
}
const triple = multiplier(3);
triple(5); // 15This pattern — a higher-order function — is common for configuration: minLength(4) returns a validator, debounce(fn, 300) returns a debounced function, Express’s rateLimit({ … }) returns middleware.
this in functions
If a function uses this, you can declare its type as a fake first parameter (it disappears from the JavaScript output):
function onClick(this: HTMLButtonElement, event: MouseEvent) {
this.disabled = true;
}Arrow functions don’t have their own this, which is one reason they’re preferred for callbacks.
The Function type — don’t use it
Function (capital F) accepts any function and lets you call it with any arguments, returning any. It’s as unsafe as any. Write the specific shape instead: () => void, (value: string) => boolean, and so on.
Remember: annotate parameters, consider annotating return types, name function shapes you reuse — and let context type your callbacks.
A tiny form validator
Define type Validator = (value: string) => string | null — a validator returns an error message, or null if the value is fine. Write: required, a Validator that rejects empty or whitespace-only text; minLength(n: number): Validator, a function that *returns* a validator; matches(pattern: RegExp, message: string): Validator; and validate(value: string, validators: Validator[]): string[], which runs every validator and returns all the error messages. Check a username against [required, minLength(4), matches(/^[a-z0-9_]+$/, "lowercase letters, digits and _ only")] for the inputs "", "Ab" and "asha_99", printing OK or the errors joined with ; .
type Validator = (value: string) => string | null;
// required, minLength, matches
// validate
// Try ittype Validator = (value: string) => string | null;
const required: Validator = (value) =>
value.trim().length > 0 ? null : "is required";
function minLength(n: number): Validator {
return (value) => (value.length >= n ? null : `must be at least ${n} characters`);
}
function matches(pattern: RegExp, message: string): Validator {
return (value) => (pattern.test(value) ? null : message);
}
function validate(value: string, validators: Validator[]): string[] {
const errors: string[] = [];
for (const check of validators) {
const error = check(value);
if (error !== null) errors.push(error);
}
return errors;
}
const usernameRules = [required, minLength(4), matches(/^[a-z0-9_]+$/, "lowercase letters, digits and _ only")];
for (const input of ["", "Ab", "asha_99"]) {
const errors = validate(input, usernameRules);
console.log(`${JSON.stringify(input)}: ${errors.length === 0 ? "OK" : errors.join("; ")}`);
}Summary
- Annotate each parameter, and optionally the return type:
function f(a: number): string. - Arrow functions use the same syntax:
(a: number): string => …. - A function type looks like
(value: string) => boolean; name it with a type alias to reuse it. - Callbacks passed to typed functions get their parameter types from context — no annotations needed.
- A function returning
voidsignals “ignore the result”; functions can also return functions.