Arrow Functions and Function Types
Type arrow functions and describe function shapes with a type alias.
Syntax
type BinaryOp = (a: number, b: number) => number;Arrow functions are typed just like regular functions. You can also describe a function's signature as a type, which is useful for callbacks and variables that hold functions.
Function type syntax
(a: number, b: number) => number describes a function that takes two numbers and returns a number.
Example
Loading editorβ¦
Press Run to execute the code.
When to use it
- A React component stores a typed event handler as a const arrow function annotated with the correct event type.
- A higher-order function accepts a typed function type alias as a parameter, making the callback contract explicit.
- A utility library exports arrow functions with annotated types so consumers see full parameter and return information.
More examples
Typed arrow function
Declares typed arrow functions with inline parameter and return annotations, equivalent to typed function declarations.
const double = (n: number): number => n * 2;
const greet = (name: string): string => `Hello, ${name}!`;
console.log(double(5)); // 10
console.log(greet('TS')); // 'Hello, TS!'Function type alias
Defines a function type alias and uses it to annotate variables and a higher-order function parameter.
type Transform = (input: string) => string;
const toUpper: Transform = (s) => s.toUpperCase();
const trim: Transform = (s) => s.trim();
function apply(fn: Transform, value: string): string {
return fn(value);
}
console.log(apply(toUpper, ' hello '));Arrow in array methods
Uses typed inline arrow callbacks with array methods, showing how TypeScript infers types from the callback context.
interface Product { name: string; price: number; }
const products: Product[] = [
{ name: 'Pen', price: 1.99 },
{ name: 'Book', price: 12.99 },
];
const expensive = products.filter((p): p is Product => p.price > 5);
const names = products.map((p) => p.name); // string[]
Discussion