AI Hints
Home›TypeScript Tutorial›More About Functions
TypeScript · Lesson 17 of 120

Function Types

Functions as values.

⏱ 2 min read▶ Video at 13:47🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Functions can be stored in variables, and passed to other functions. Their type describes the parameters, and what they return, with an arrow.

Function Types
From the video: Function Types
  • Functions are values
  • Passed around
  • Arrow types

A discount function type

Discount is a function type, it takes a number, and returns a number. Two discounts match it. Apply takes a price and any discount. Run it.

app.tstypescript
type Discount = (price: number) => number;

const tenPercent: Discount = price => price * 0.9;
const fiveOff: Discount = price => price - 5;

function apply(price: number, discount: Discount) {
  return discount(price);
}

console.log(apply(100, tenPercent), apply(100, fiveOff));
Output
90 95

A function that does not fit

This discount returns text instead of a number. Run it. It doesn't match the discount type.

app.tstypescript
type Discount = (price: number) => number;
const broken: Discount = price => `${price} off`;
Output
app.ts line 2: Type 'string' is not assignable to type 'number'.

Summary

Function types describe parameters and the return type, with an arrow. Next, void and never.

Key takeaways
  • (price: number) => number
  • Pass functions
  • Checked
Next up: void and never — nothing, and never