Function Types and Arrow Functions

Function Type Syntax

A function type looks like an arrow: (a: number, b: number) => number. Use it for callbacks and variables that hold functions.

Example

When a function is passed where a function type is expected, its parameters are typed automatically (contextual typing), so a and b below need no annotations.

type PriceRule = (price: number) => number;

const tenPercentOff: PriceRule = (price) => price * 0.9;
const flat100Off: PriceRule = (price) => Math.max(0, price - 100);

function applyRules(price: number, rules: PriceRule[]): number {
  return rules.reduce((current, rule) => rule(current), price);
}

console.log(applyRules(1000, [tenPercentOff]));
console.log(applyRules(1000, [tenPercentOff, flat100Off]));

const sorted = [499, 89, 1299].sort((a, b) => a - b);
console.log(sorted);

Output

900
800
[ 89, 499, 1299 ]

Arrow Functions

Example

Arrow functions take types the same way. A short arrow returning an object must wrap it in parentheses.

const square = (n: number): number => n * n;
const toItem = (name: string, price: number) => ({ name, price });
const log = (msg: string): void => console.log("[LOG]", msg);

console.log(square(12));
console.log(toItem("Pen", 20));
log("checkout started");

Output

144
{ name: 'Pen', price: 20 }
[LOG] checkout started

Callback With the Wrong Signature

Example

The callback must return a number; returning a string fails (TS2322).

type PriceRule = (price: number) => number;
const bad: PriceRule = (price) => "Rs. " + price;

Compiler output (tsc)

Line 2: error TS2322: Type 'string' is not assignable to type 'number'.