Function types

Topic 3 of 4 in Objects and functions7 min readIntermediateFree course

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

Anatomy of a typed function: function total(prices: number[], tax = 0.2): number { … }. prices: number[] is a parameter type; tax = 0.2 is a default, inferred as number and optional; the : number after the brackets is the return type. A function type describes any function with that shape: type Pricer = (prices: number[], tax?: number) => number; const total: Pricer = (prices, tax = 0.2) => 0; — the parameters are typed from Pricer.

TypeScript
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: tax is a number.
  • 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 return inside the function rather than at every call site.

Calls are checked against all of it:

TypeScript
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:

TypeScript
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:

TypeScript
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:

TypeScript
const alwaysZero: Formatter = () => "0";   // ✓ fine to ignore `value`

Function types can also be written as a method or call signature inside an object type:

TypeScript
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:

TypeScript
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:

TypeScript
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:

TypeScript
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; ignored

Functions that return functions

Functions are values, so they can create and return other functions. The return type is just a function type:

TypeScript
function multiplier(factor: number): (n: number) => number {
  return (n) => n * factor;
}

const triple = multiplier(3);
triple(5);   // 15

This 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):

TypeScript
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.

Exercise

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 ; .

TypeScript
type Validator = (value: string) => string | null;

// required, minLength, matches

// validate

// Try it

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 void signals “ignore the result”; functions can also return functions.