Sub topic 5
Describing functions and callable objects
This chapter assumes you know basic TypeScript annotations, how JavaScript functions and objects work, and that you have read the chapters on interface declarations and type aliases. Here you will see how both constructs describe functions, and what a function type means for assignability.
Two ways to write the same function type
A function type states the parameters a function accepts and the value it returns. A type alias writes it with arrow syntax. An interface writes it as a call signature, which is a member with no name.
interface Formatter {
(input: string): string;
}
type FormatFn = (input: string) => string;
const upper: Formatter = (s) => s.toUpperCase();
const trim: FormatFn = (s) => s.trim();
console.log(upper("ada"), trim(" grace "));The two declarations are interchangeable. The parameter s needs no annotation in either case because TypeScript infers it from the declared type. This is called contextual typing.
Parameter names in a function type are documentation only. (input: string) => string and (text: string) => string are the same type. Editors show the names in hover text, so choose meaningful ones.
For a plain function, the alias is shorter and is the usual choice. The interface form earns its place when the value is more than a function.
What assignability checks for functions
TypeScript applies the same shape-based rule to functions as to objects: a function is accepted if it can safely be used where the declared type is expected. Three consequences surprise people.
type Callback = (value: number, index: number) => void;
const onlyValue: Callback = (value) => {
console.log(value);
};
const returnsString: Callback = (value) => String(value);
// const needsThree: Callback = (a: number, b: number, c: number) => {};
// error: Target signature provides too few arguments.
[10, 20].forEach(onlyValue);- A function may declare fewer parameters than the type lists. The caller passes extra arguments, and the function ignores them. This is why
forEach(x => ...)works. - A function may not require more parameters than the type promises.
- When the declared return type is
void, a function that returns a value is still accepted. The return value is discarded by the caller. This rule applies to the contextual type only. A function declaration annotated: voidcannot return a string.
Parameter types are compared in the opposite direction from what many people expect. A function that accepts a wider input can stand in for one that accepts a narrower input, but not the reverse. A function taking string | number can be used where (x: string) => void is expected. The next sections show where this rule bends.
Callable objects with properties
In JavaScript a function is an object, so it can carry properties. Libraries use this often: a function that also has .cancel(), .displayName, or .default. An object type with a call signature and other members describes this.
interface Counter {
(step?: number): number;
reset(): void;
readonly label: string;
}
function makeCounter(label: string): Counter {
let count = 0;
const next = (step: number = 1): number => {
count += step;
return count;
};
const reset = (): void => {
count = 0;
};
return Object.assign(next, { reset, label });
}
const clicks = makeCounter("clicks");
clicks();
clicks(5);
console.log(clicks.label, clicks()); // clicks 7
clicks.reset();Object.assign returns the function type intersected with the properties object. That result satisfies Counter, so no cast is needed.
A type alias can express the same thing with an object type literal:
type CounterAlias = {
(step?: number): number;
reset(): void;
readonly label: string;
};A function type written with arrow syntax cannot carry extra members. Once you need properties next to the call, switch to the object form, either as an interface or as an alias containing braces.
Overloads in a call signature
An interface may contain several call signatures. Each one is an overload, and callers see the list in the order written.
interface Parse {
(input: string): number;
(input: string[]): number[];
}
function parseImpl(input: string): number;
function parseImpl(input: string[]): number[];
function parseImpl(input: string | string[]): number | number[] {
return Array.isArray(input) ? input.map(Number) : Number(input);
}
const parse: Parse = parseImpl;
const one = parse("42"); // number
const many = parse(["1", "2"]); // number[]
console.log(one, many);Assigning a single arrow function to Parse usually fails. The arrow's one signature must satisfy every overload, and a function returning number | number[] does not. A function declaration with overload signatures, as above, is the dependable way to produce a value of an overloaded type.
TypeScript tries overloads from top to bottom and picks the first match. Put the more specific signature first.
Construct signatures
A construct signature starts with new and describes something you can call with new. This lets you accept a class as a parameter.
interface Clock {
now(): number;
}
interface ClockFactory {
new (offset: number): Clock;
}
class OffsetClock implements Clock {
constructor(private offset: number) {}
now(): number {
return Date.now() + this.offset;
}
}
function build(factory: ClockFactory, offset: number): Clock {
return new factory(offset);
}
console.log(build(OffsetClock, 1000).now());The class OffsetClock itself, not an instance, matches ClockFactory. An alias form is type ClockFactory = new (offset: number) => Clock;.
Generic function types
A type parameter can sit on the whole declaration or on the call signature. The position changes when the type is chosen.
type Identity = <T>(value: T) => T; // T chosen at each call
interface Mapper<T, U> { // T and U chosen once, up front
(value: T): U;
}
const id: Identity = (value) => value;
const toLength: Mapper<string, number> = (s) => s.length;
console.log(id("x"), id(3), toLength("hello"));Identity is one function that works for any T. Mapper<string, number> is a function fixed to one input and output type. Mixing these up is a common source of errors such as "Type 'T' is not assignable to type 'T'".
Method syntax versus property syntax
Inside an object type, a function member can be written two ways. They look nearly the same but are checked differently.
interface MethodStyle {
handle(event: string | number): void;
}
interface PropertyStyle {
handle: (event: string | number) => void;
}
const narrow = (event: string): void => {
console.log(event.toUpperCase());
};
const a: MethodStyle = { handle: narrow }; // allowed
// const b: PropertyStyle = { handle: narrow };
// error under strictFunctionTypes: 'string | number' is not assignable to 'string'
console.log(typeof a.handle);With strictFunctionTypes on (part of strict), property-style members compare parameters strictly. Method-style members stay bivariant, meaning a narrower parameter type is accepted. That is unsafe here: a.handle(42) would call narrow with a number and fail at runtime on toUpperCase.
Unions of function types
Arrow syntax extends as far right as it can. Without parentheses, a union attaches to the return type.
type Wrong = () => string | null; // a function returning string | null
type Right = (() => string) | null; // either a function or null
const lazy: Right = () => "value";
const none: Right = null;
console.log(lazy?.(), none);Only an alias can name a union, so optional or alternative callbacks belong in an alias.
Choosing a form
Common errors
- Writing
() => string | nullwhen you meant a nullable function. Add parentheses. - Assigning one arrow function to an overloaded interface. Use a declaration with overload signatures.
- Expecting the parameter names to matter. They do not.
- Using method syntax for handlers and losing strict parameter checks.
- Putting properties on an arrow-syntax type. Use an object type with a call signature.
Exercise
Given interface Handler { run(x: string | number): void } and type Handler2 = { run: (x: string | number) => void }, you assign { run: (x: string) => {} } to each with strict on. Which assignment compiles, and why?
Show answer
The assignment to Handler compiles, and the assignment to Handler2 fails. run in Handler uses method syntax, so its parameters are compared bivariantly and the narrower string is accepted. run in Handler2 uses property syntax with a function type, so strictFunctionTypes requires the function to accept every string | number, and (x: string) => {} does not.
Exercise
Write a type for a function debounced that takes a string and returns void, and also has a cancel(): void method. Should it be written with arrow syntax alone?
Show answer
No. Arrow syntax cannot carry extra members. Use interface Debounced { (value: string): void; cancel(): void; }, or the same body in a type alias with braces.