typescript · level 3 · unit 1 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A function is a value you can store and pass around.
In Level 1 every function started with the word function. There is a shorter way to write one: the . (price: number): number => price + 3 takes a price and hands back the price plus postage. The => arrow points from the parameters to the answer.
Functions are values, so they fit in boxes and can be passed to other functions. A function you pass in for another function to call is a . Its label is a , like (price: number) => number: what goes in, then what comes out.
The checker compares every callback with its function type. A callback that takes or hands back the wrong thing is stopped before anything runs.
const addPostage = (price: number): number => price + 3;
function applyToAll(prices: number[], change: (price: number) => number): number[] {
const result: number[] = [];
for (const price of prices) {
result.push(change(price));
}
return result;
}
console.log(addPostage(10));
console.log(applyToAll([10, 25], addPostage)); Pass the box name, addPostage, with no brackets. Brackets would call it straight away and pass its answer instead.
guess first
Two styles, one function. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
const shout = (word: string): string => word.toUpperCase() + "!";
const whisper = (word: string): string => word.toLowerCase() + "...";
function speak(word: string, style: (word: string) => string): void {
console.log(style(word));
}
speak("Hello", whisper);
speak("Hello", shout);
your turn
Your turn. Write a callback for a sale.
Name your callback, write what it hands back for each price (half price, or a few pounds off), then pass it to applyToAll.
fix it
The pet greeter will not run. Fix the callback.
- Read the error:
TS2345says the callback does not fit the function type(pet: string) => void. eachPethands each callback a pet name, which is a string. What doesgreetexpect?- On line 6, change
pet: numbertopet: string, then press run.
nailed it
your functions can travel now. :D
(a: number): number => a * 2is an arrow function.- A function type, like
(pet: string) => void, labels a callback. - The checker rejects callbacks that take or return the wrong types.
new words in your collection
- arrow function
- function type
- callback
This lesson isn’t saved. A free account remembers every lesson you finish.