Function Types
TypeScript lets you describe the type of a function — its parameters and return value.
Function Type Syntax
// Inline
let add: (a: number, b: number) => number
add = (x, y) => x + y // parameter names don't need to match
// Type alias
type BinaryOp = (a: number, b: number) => number
const multiply: BinaryOp = (a, b) => a * b
const divide: BinaryOp = (a, b) => a / b
Callbacks
function transform(
arr: number[],
fn: (item: number) => number
): number[] {
return arr.map(fn)
}
transform([1, 2, 3], x => x * 2) // [2, 4, 6]
Generic Functions
function identity<T>(value: T): T {
return value
}
identity<string>('hello') // 'hello' (type: string)
identity(42) // 42 (type: number — inferred)