TypeScript Reference ยท Primitive and Special Types
The Function type in TypeScript
The global Function type in TypeScript accepts any callable but checks nothing about arguments or results. Learn why to avoid it and what to use instead.
Function is a built-in interface that describes every function value. It has members such as call, apply, bind and length. A value of type Function can be called, but TypeScript knows nothing about its parameters or return value, so the call is checked as if it returned any.
That makes Function an escape hatch, much like any for callables. Almost always you should describe the real signature, such as (a: number) => string, or use a generic constraint on the function type.
let f: Function = (a: number) => a * 2; const r = f(1, 2, 3); // no error, r is any
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
let f: Function; let g: (x: number) => string; // preferred let h: { (x: number): string }; // call signature form
| Part | Description |
|---|---|
Function |
The global interface for all functions and classes. Has apply, bind, call, toString, length, name. |
(x: T) => R |
A function type with a checked signature. |
Edge cases:
- Calling a
Function-typed value is allowed without any argument checking, and its result isany. - Classes (constructors) are also assignable to
Function, so the type does not even guarantee that the value can be called withoutnew. newon aFunction-typed value is also accepted and givesany.
Usage notes
- Avoid
Function. The lint rule@typescript-eslint/no-unsafe-function-typeflags it. It silently disables argument and return checks. - Use specific signatures. Describe parameters and results:
(event: string) => void. - Use
(...args: never[]) => unknownfor "any function" constraints. This accepts every function as a generic bound without making calls unsafe. Use(...args: any[]) => anyonly when you must. - Use
Parameters<F>andReturnType<F>. These utilities recover real types from a generic function parameter. typeof x === "function"narrows anunknownvalue to something callable; combine it with a type guard if you need a particular signature.- Method borrowing.
Function.prototype.call/apply/bindare typed throughstrictBindCallApply, which is on understrict. That checks them when the function has a real type.
Related
- Function types, Call signatures,
any,object - Lessons: Function types, Functions, Generic constraints