Sub topic 4
Describing functions with function types
This chapter assumes you can write TypeScript functions with annotated parameters and return types, and that you know object types and union types. You should also have a compiler or editor available, because several examples are meant to be broken on purpose.
A function type describes the shape of a function without implementing it. You use function types to type callbacks, parameters, object properties, variables, and the return values of other functions.
Function type expressions
The shortest form is the function type expression. It looks like an arrow function with the body replaced by a type.
type BinaryOp = (a: number, b: number) => number;
const add: BinaryOp = (x, y) => x + y;
const multiply: BinaryOp = (left, right) => left * right;
console.log(add(2, 3), multiply(2, 3)); // 5 6Three rules explain most of what you will see:
- The parameter names in a function type are documentation only.
addusesxandy, and that is fine. - The return type is required.
(a: number) =>is a syntax error. Write=> voidif the function returns nothing useful. - The
=>separates parameters from the return type. This differs from an object type, where a call signature uses:(covered below).
The compiler checks the implementation against the type. Because add is declared as BinaryOp, the arrow function's parameters are typed from context, and a wrong return type is reported at the function.
type BinaryOp = (a: number, b: number) => number;
// error: Type 'string' is not assignable to type 'number'.
const broken: BinaryOp = (a, b) => `${a}${b}`;Unnamed parameters
A frequent mistake is writing only a type in the parameter list.
type Handler = (string) => void; // 'string' is the NAME of a parameter of type any
type Fixed = (value: string) => void;In Handler, string is a parameter name, and its type is implicitly any. With noImplicitAny (part of strict) the compiler reports an error. Always write name: Type.
Using aliases for reuse
A function type written inline works, but an alias gives a callback shape a name that you can reuse and read.
type Comparator<T> = (a: T, b: T) => number;
const byLength: Comparator<string> = (a, b) => a.length - b.length;
function sortCopy<T>(items: T[], compare: Comparator<T>): T[] {
return [...items].sort(compare);
}
console.log(sortCopy(["ccc", "a", "bb"], byLength)); // [ 'a', 'bb', 'ccc' ]Comparator<T> is a generic alias. The type parameter belongs to the alias, so each use fixes T once. Generics get a full chapter later. Here, notice only that Comparator<string> is an ordinary function type.
Call signatures in object types
A function type expression cannot describe a function that also carries properties. JavaScript functions are objects, so this is common: a function with a language field, a counter with a reset method, a library entry point with helper methods attached.
For that case, write a call signature inside an object type.
type Greeter = {
(name: string): string;
language: string;
};
const greeter: Greeter = Object.assign(
(name: string) => `Hello, ${name}`,
{ language: "en" }
);
console.log(greeter("Ada"), greeter.language); // Hello, Ada enThe call signature (name: string): string uses a colon before the return type. An interface can hold the same signature.
interface Counter {
(): number;
reset(): void;
}
function makeCounter(): Counter {
let count = 0;
const counter = (() => ++count) as Counter;
counter.reset = () => {
count = 0;
};
return counter;
}
const c = makeCounter();
c();
c();
console.log(c()); // 3
c.reset();
console.log(c()); // 1The as Counter assertion is needed because the arrow function does not yet have a reset property when it is created. The assertion tells the compiler you will add it immediately. Object.assign in the previous example avoids the assertion because it returns the intersection of its two arguments.
Several call signatures
An object type can list more than one call signature. The compiler tries them from top to bottom and uses the first one that matches the arguments.
type Parse = {
(input: string): number;
(input: string[]): number[];
};
const parse: Parse = (input: string | string[]): any =>
Array.isArray(input) ? input.map(Number) : Number(input);
const one = parse("42"); // number
const many = parse(["1", "2"]); // number[]
console.log(one, many); // 42 [ 1, 2 ]The implementation is typed loosely here, since the compiler checks the implementation only for compatibility with each signature. Function overloads for declared functions work the same way and get their own chapter.
Generic function types
A function type can have its own type parameters. Where you put them changes the meaning.
type IdentityA = <T>(value: T) => T;
type IdentityB<T> = (value: T) => T;
const idA: IdentityA = value => value;
const idB: IdentityB<number> = value => value;
idA("text"); // T is chosen per call: string
idA(5); // T is chosen per call: number
idB(5); // T was fixed to number when the alias was used
// idB("text"); // error: Argument of type 'string' is not assignable to parameter of type 'number'With IdentityA, the function itself is generic, and each call picks its own T. With IdentityB<number>, the type is a specific, non-generic function. Use the first form when the function must work for any type at each call. Use the second form when a surrounding context, such as a class or an alias, decides the type once.
Construct signatures
A signature that starts with new describes something you call with new.
type Factory<T> = new (name: string) => T;
class Dog {
constructor(public name: string) {}
}
function create<T>(ctor: Factory<T>, name: string): T {
return new ctor(name);
}
const rex = create(Dog, "Rex"); // Dog
console.log(rex.name); // RexPass the class itself, Dog, not an instance. Factory<T> accepts any constructor that takes a string and builds a T.
Function types and the `typeof` operator
When a function already exists, you can derive its type instead of repeating it.
function area(width: number, height: number): number {
return width * height;
}
type AreaFn = typeof area; // (width: number, height: number) => number
const alt: AreaFn = (w, h) => w * h * 1;This keeps the alias in step with the function. If you change area, AreaFn changes with it.
Common errors
| Symptom | Cause | Fix | Column | Column |
|---|---|---|---|---|
| "Parameter 'x' implicitly has an 'any' type" in a type alias | A parameter list has only a type, as in `(string) => void` | Write `(x: string) => void` | ||
| "Type '...' has no call signatures" | A value typed as a union, object, or `unknown` is called as a function | Narrow it to a function first, or add a call signature to its type | ||
| "Property 'reset' is missing" when returning a function | A function value lacks properties its declared type requires | Use `Object.assign`, or assign the property and assert the type | ||
| A generic alias fixes `T` too early | `type F<T> = (x: T) => T` was used where `<T>(x: T) => T` was meant | Move the type parameter to the signature | ||
| Parentheses missing in a union | `() => string | number` means a function returning a union | Write `(() => string) | number` for a union of a function and a number |
The last row is easy to miss. An arrow in a type extends as far right as it can, so a union after it belongs to the return type.
type ReturnsUnion = () => string | number; // one function type
type UnionOfTwo = (() => string) | number; // a function, or a numberChoosing a form
- Use a function type expression for plain callbacks and parameters. It is shortest and covers most cases.
- Use an object type or interface with call signatures when the function has properties, or several call shapes.
- Use a construct signature when the value is a class or factory called with
new. - Use
typeof existingFunctionwhen a type should track an implementation you already have.
Exercise
Write a type Middleware for a function that can be called as mw("x") and returns a string, and that also has a name: string property. Then explain why type Middleware = (input: string) => string cannot express it.
Show answer
Use a call signature in an object type:
type Middleware = {
(input: string): string;
name: string;
};
A function type expression has only parameters and a return type, so it has nowhere to declare the extra name property. An object type with a call signature lists both the call shape and the properties.
Exercise
What is the difference between type A = <T>(x: T) => T and type B<T> = (x: T) => T? Which one allows f("a") and f(1) on the same function value?
Show answer
In A, the type parameter belongs to the function, so each call picks its own T, and one value of type A can be called with both "a" and 1. In B<T>, T is fixed when the alias is used, so B<number> accepts only numbers. Type A allows both calls on the same value.