All lessons

Power Tools: Typed Arrays & Union Types

9 min · TypeScript

Type your arrow functions, map over typed arrays, and narrow union types.

TypeScript · Power Tools: Typed Arrays & Union Types0/5 cleared

Enemy 1 of 5

This arrow function takes a number and returns a number, with both types written out. It squares 6. Press Run to see it.

Why this works

You've already seen arrow functions written without types elsewhere, and typed functions using the function keyword. This is where the two meet: an arrow function can be typed just as fully as a regular one, with parameter types and a return type: (n: number): number => n * n.

TypeScript checks that the parameter and return types match wherever the arrow function is called, exactly as it would for a function written with the function keyword. The shorter arrow syntax doesn't cost you any type safety, it's purely a different way to write the same thing.

You
Binary Treant
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.