Summary
In this lesson, you learned that:
- Every parameter needs a type:
function heal(health: number, amount: number). Without one, TypeScript reportsParameter 'health' implicitly has an 'any' type.(TS7006). Every call is checked: a wrong argument gives TS2345. - The return type goes after the parentheses:
function damage(power: number, armor: number): number {. TypeScript works it out when you leave it out. When you write it, TypeScript checks the body against it: a branch withoutreturngives TS2366, a value of the wrong type TS2322. voidis the return type of functions that return nothing:function printHero(name: string): void. Their result can't be used, for exampletitle.toUpperCase()givesProperty 'toUpperCase' does not exist on type 'void'.If you need a value, return it.- A call must pass as many arguments as the function has parameters:
Expected 2 arguments, but got 1.(TS2554). When you add a parameter, TypeScript shows every call that has to change. - An optional parameter has a question mark:
title?: string. Inside, its type isstring | undefined, so check it before using it:if (title === undefined) { ... }. Optional parameters go last. - A parameter with a default value,
power: number = 10or justpower = 10, is optional too, but inside the function it's neverundefined. - Arrow functions have their types in the same places:
const double = (n: number): number => n * 2;. A parameter with a type needs parentheses. - A function has a type too:
(power: number) => number. It can be named,type Strike = (power: number) => number;, and used for parameters that hold a function. Pass the function itself, without parentheses. mapcreates a new array from the results of a function:chests.map(gold => gold * 2).filterkeeps the elements for which the function returnstrue:monsters.filter(monster => monster.power > 10). The parameter gets its type from the array, so it needs no annotation.
In the next lesson, Object Types, you'll describe what objects look like: which properties they have and of which types. TypeScript will then check every hero, item and monster in your program.
Instructions
Let's practice. Write an arrow function, stored in const heal, with the parameters health and amount, both of type number, a parameter maxHealth with the default value 50, and the return type number. It returns health + amount, but never more than maxHealth.
Print heal(20, 15), heal(40, 35) and heal(40, 35, 100). The program prints:
35
50
75Use filter to keep the potions that heal more than 15, and then map to turn each of them into a text like +20 health. Store the result in labels. Then write a function printAll with a parameter lines of type string[] and the return type void, which prints each element of lines on its own line, and call printAll(labels). At the end, the program prints:
+20 health
+35 health
+50 healthStart programming for free
10/10