Three Ways to Type a Function Signature
Function Types
Functions can be typed inline, with `type` aliases, or with interfaces. Pick the form that reads best.
What you'll learn
- Author function types
- Type a callback parameter
- Recognize the shorthand and verbose forms
A function type describes a callable signature — the parameter types and return type. There are several ways to write one.
Inline — On the Function Itself
function add(a: number, b: number): number {
return a + b;
}
const greet = (name: string): string => `Hi, ${name}`; The most common form. Annotations go where the function is defined.
As a Type Alias — Arrow Style
type Adder = (a: number, b: number) => number;
const add: Adder = (a, b) => a + b; Useful when:
- The same signature is used in multiple places
- You’re typing a variable that holds a function
- The callback shape is a public API
Note the => (NOT :) between parameters and return type.
As an Interface
interface Adder {
(a: number, b: number): number;
} Same meaning as the type alias. Used when:
- The function also has properties (rare)
- You want declaration merging
- The codebase prefers interfaces
Callback Parameters
function map<T, U>(arr: T[], fn: (item: T) => U): U[] {
// ...
} fn: (item: T) => U is an inline function type. Read as:
“a function that takes an item of type T and returns a U”.
Methods on Object Types
type Logger = {
log(msg: string): void; // method shorthand
warn: (msg: string) => void; // arrow style
}; Both forms work. The arrow style is slightly stricter about contravariance (rarely matters in app code).
Optional Parameters
type Greet = (name: string, punctuation?: string) => string; ?: makes the parameter optional. We dig into this in a couple of
lessons.
Up Next
Annotating function parameters in detail.
Parameter Types →