Function type expressions and call signatures
Describing the type of a function itself, from the arrow syntax to call signatures for functions with properties and construct signatures for classes.
Parameter and return typesObject types, optional and readonly properties
Function type expressions and call signatures
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Functions are values, so they need types of their own; a function type expression such as `(a: number, b: number) => number` describes any function with that parameter list and return type.
- Parameter names are required in a function type but don't have to match the implementation's names; only the positions and types are checked.
- Giving a function type a name with a type alias lets many implementations share one contract, and an arrow function assigned to that type gets its parameter types by contextual typing.
- A call signature, written `{ (x: number): string }` with a colon instead of an arrow, describes a function inside an object type, which is how you type a function that also carries properties.
- A construct signature, `new (name: string) => Logger` or `{ new (name: string): Logger }`, describes something that must be called with `new`, such as a class passed as an argument to a factory.
- A function declaration can't be annotated with a function type directly; to apply a named function type, assign a function expression or arrow function to a `const` of that type.
Functions are values, so they need types
In JavaScript a function is a value like any other. You store it in a variable, pass it as an argument, return it from another function, put it in an object. The previous lessons typed a function’s parameters and return value. The moment you pass a function around, you need a type for the function itself, so that whoever receives it knows how it can be called.
Think of a power socket. The socket doesn’t care which appliance you plug in. It only fixes the shape of the plug. A function type is that socket shape: it says what arguments the function takes and what it gives back, and any function with a matching shape fits.
Function type expressions
The most common form looks like an arrow function with types instead of a body:
type Compare = (a: number, b: number) => number;
const ascending: Compare = (x, y) => x - y;
const descending: Compare = (x, y) => y - x;
[3, 1, 2].sort(ascending);
Read Compare as “a function that takes two numbers and returns a number.” A few details matter.
Parameter names are required, but they’re only labels. The implementation above uses x and y while the type says a and b, and that’s fine. Only positions and types are compared. Leaving the name out is a classic mistake: (string) => void declares a parameter named string with no type, which strict reports as an implicit any.
Contextual typing fills in the implementation. Because ascending is declared as Compare, its parameters are number without annotations, and its return is checked against number. Write (x, y) => String(x - y) and the error appears on that line.
One type, many implementations. This is the payoff the video focuses on. When several functions must follow the same contract — comparators, event handlers, validation rules — a named type keeps them consistent and gives you one place to change it.
A function declaration has no slot for a type like Compare. If you want to apply a named function type, write a function expression or arrow function and assign it to a const of that type.
Call signatures: functions that carry properties
JavaScript functions are objects, so they can have properties. A memoized function might expose a cache; a debounced one, a cancel method. A function type expression can’t describe those extra members. A call signature can, because it lives inside an object type:
type Counter = {
(step?: number): number;
reset: () => void;
readonly label: string;
};
function makeCounter(label: string): Counter {
let count = 0;
const next = (step = 1) => (count += step);
return Object.assign(next, {
reset: () => {
count = 0;
},
label,
});
}
const clicks = makeCounter("clicks");
clicks();
clicks(5);
clicks.reset();
console.log(clicks.label);
Note the syntax difference: inside an object type, a call signature uses a colon between the parameter list and the return type, (step?: number): number, not =>. The same thing works in an interface, which is how many library type definitions describe callable objects.
TypeScript also understands properties assigned directly onto a declared function, so function next() {...} followed by next.label = "clicks" is typed correctly too. Object.assign keeps it to one expression.
Construct signatures: things you call with new
Classes are values too, and sometimes you pass one as an argument — a plugin system that instantiates whatever class you give it, say. Its type isn’t a call, because calling a class without new throws. TypeScript has a separate form for this, the construct signature:
interface Logger {
log(message: string): void;
}
class ConsoleLogger implements Logger {
prefix: string;
constructor(prefix: string) {
this.prefix = prefix;
}
log(message: string) {
console.log(`${this.prefix} ${message}`);
}
}
type LoggerClass = new (prefix: string) => Logger;
function createLogger(Ctor: LoggerClass, prefix: string): Logger {
return new Ctor(prefix);
}
const logger = createLogger(ConsoleLogger, "[app]");
logger.log("started");
new (prefix: string) => Logger reads “something you call with new, passing a string, that produces a Logger.” The object-type form is { new (prefix: string): Logger }, and an object type can hold both a call signature and a construct signature at once. The built-in Date works that way: Date() returns a string, while new Date() returns a Date.
You’ll reach for construct signatures less often than call signatures, but they’re the reason a factory function can accept “any class with this constructor” in a type-safe way.
About the video
Benny’s video is short and stays on the first half of this lesson. It opens with the use case — several functions that should share one shape — then builds a reusable function type and applies it to implementations, and finishes on why that’s worth doing. It doesn’t cover functions with properties or construct signatures, so those sections are carried by the text here. Net Ninja’s video in the links is a slower, beginner-paced walkthrough of function type expressions if you want more examples of matching signatures.
Check yourself
In the type `type Handler = (string) => void`, what is `string`, and what does `strict` say about it?
It is a parameter name, not a type. TypeScript reads `(string) => void` as a function with one parameter called `string` whose type is unspecified, so it is implicitly `any`. Under `strict` this is reported as an error suggesting you meant something like `(arg0: string) => void`. Function type parameters always need a name and a type.
Given `type Compare = (a: number, b: number) => number`, why does `const byValue: Compare = (x, y) => x - y` compile without annotating `x` and `y`?
The variable's declared type supplies the context. TypeScript matches the arrow function's parameters to the type's parameters by position, so `x` and `y` are both `number`, and it checks that `x - y` returns a `number`. The names in the type and in the implementation are free to differ.
When would you write a call signature `{ (input: string): string; calls: number }` instead of a function type expression?
When the value is a function that also has properties. A function type expression can only describe the callable part. A call signature lives inside an object type, so it can sit next to property declarations like `calls: number`, describing a function you can both call and read fields from.
What does the type `new (url: string) => Connection` describe, and why can't a plain function type describe the same thing?
It describes something you call with `new`, passing a string and getting back a `Connection`, which is what a class constructor is. A plain function type `(url: string) => Connection` describes a call without `new`, and calling a class without `new` throws at runtime, so the two are not interchangeable and TypeScript keeps them separate.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.