×

typescript · level 2 · unit 4 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

An is a short way to write a function.

You can write a function as an arrow function and keep it in a const box: const double = (n: number): number => n * 2;. The parameters sit in brackets, then =>, then the answer. With no curly brackets, the value after the arrow is returned for you.

Need several lines? Add curly brackets and a return, as in a normal function. Either way, call it as before: double(4).

A function's own type is written the same way: (n: number) => number means it takes a number and gives back a number.

const double = (n: number): number => n * 2;
const greet = (name: string): string => `Hi, ${name}!`;
const total = (a: number, b: number): number => {
  const sum = a + b;
  return sum;
};
console.log(double(4));
console.log(greet("Ola"));
console.log(total(3, 9));

Read => as “gives”: n gives n times 2.