TypeScript Reference ยท Literal and Object Types
TypeScript function types
Reference for TypeScript function types: arrow type syntax, call signatures in interfaces, return types, void, never, callbacks and generic function types.
A function type describes the parameters a function accepts and the value it returns, without implementing it. The common form is the arrow syntax (a: number, b: number) => number. You can use it for variables, parameters (callbacks), properties and type aliases.
A function type can also be written as an object type with a call signature: { (a: number): string }. This form is needed when a function also has properties, or when it has several call signatures (overloads).
type BinaryOp = (a: number, b: number) => number; const add: BinaryOp = (a, b) => a + b;
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
type F1 = (param: Type, optional?: Type, ...rest: Type[]) => ReturnType; type F2 = { (param: Type): ReturnType }; // call signature type F3 = new (param: Type) => Instance; // construct signature type F4 = <T>(value: T) => T; // generic type F5 = (this: Context, arg: Type) => void; // with this
| Part | Description |
|---|---|
| Parameters | Names are required in the syntax but do not matter for compatibility. May be optional or rest. |
| Return type | Required after =>. Use void for "result is ignored", never for "never returns". |
new |
Marks a construct signature: the type describes a class or constructor function. |
Edge cases: a function type () => void accepts functions returning any value, but a function declaration annotated : void may not return one. Parameter compatibility is contravariant under strictFunctionTypes for arrow-typed members.
Usage notes
- Inference: contextual typing gives lambda parameters their types from the surrounding function type, so you rarely annotate them.
- Return type
unknownvsany: preferunknownfor callbacks whose result you will not use. - Overloads: a type with several call signatures describes an overloaded function; see Function overloads.
- Utility types:
Parameters<F>,ReturnType<F>andAwaited<ReturnType<F>>extract pieces from function types. - Methods vs properties: see Method signatures for variance differences.
- Common mistake:
() => { a: number }is parsed as a function with a block body when written as an expression; in a type it is fine, but a value like() => ({ a: 1 })needs parentheses.