typescript · level 2 · unit 4 · lesson 1
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
A one-line arrow. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
const isAdult = (age: number): boolean => age >= 18;
const ages: number[] = [12, 18, 40];
for (const age of ages) {
console.log(age, isAdult(age));
}
your turn
Your turn. Write a tip calculator.
Finish the arrow function so it returns the bill times the tip, like 0.1 for ten per cent. Then try it on a bill of your choice.
fix it
The curly brackets ate the answer. Fix it!
- Read the error:
TS2355. The label promises a number, but nothing is returned. - With curly brackets, an arrow function needs a
return, like a normal function. - Put
returnin front ofn * non line 2, then press run.
nailed it
you can write functions the short way. :D
- An arrow function is parameters, then
=>, then the answer. - With no curly brackets, the answer is returned for you.
- With curly brackets, write
returnas usual.
new words in your collection
- arrow function
This lesson isn’t saved. A free account remembers every lesson you finish.