Codectionary / Developer documentation / TypeScript

Safe Callback Parameter Types

A callback must be able to handle every input its consumer promises to supply.

What it is and why to use it

A callback must be able to handle every input its consumer promises to supply. Under strictFunctionTypes, function parameter compatibility checks help reject a callback that only understands a narrower subtype. This is useful when designing event handlers and reusable processing functions.

Common mistakes and limitations

Method declarations have compatibility exceptions intended for common class patterns; do not assume their checking is identical to function-valued properties. Enable strict checking and prefer clear function signatures at callback boundaries.

Run this example

Use TypeScript 5.8 or later with strict checking and an ES2022 target. Save each complete example independently as example.ts, compile it, then run the generated JavaScript with a compatible Node.js installation. Compiler-only options below affect checking; they do not add runtime validation.

Terminal — compile and run

npx tsc example.ts --strict --target ES2022 --module commonjs
node example.js

Syntax

type Handler = (value: Animal) => string;

Examples

Safe Callback Parameter Types

Standalone TypeScript 5.8+ example; expected output is explained below.

type Animal = { name: string };
type Dog = Animal & { bark(): void };
const nameOf = (animal: Animal): string => animal.name;
const dogHandler: (dog: Dog) => string = nameOf;
console.log(dogHandler({ name: "Rex", bark() {} }));
  1. nameOf can handle any Animal, including a Dog.
  2. Assigning that broadly capable function as a dog-specific callback is safe.
  3. The opposite direction could fail if an ordinary Animal were passed to a function that assumes bark exists. The type relation follows accepted inputs, not just return values.
  4. Expected output: Rex

Best practices

  • Method declarations have compatibility exceptions intended for common class patterns; do not assume their checking is identical to function-valued properties. Enable strict checking and prefer clear function signatures at callback boundaries.
  • Keep external-input validation separate from compile-time type descriptions.

Runtime & versions

Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

TypeScript Handbook

Specifications & further reading