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.
Next comes a small project, the scoreboard of an archery contest, which you'll write on your own with everything from the first three lessons. Then, in the Object Types lesson, 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
- 1
Let's practice. Write an arrow function, stored in
const heal, with the parametershealthandamount, both of typenumber, a parametermaxHealthwith the default value50, and the return typenumber. It returnshealth + amount, but never more thanmaxHealth. - 2
Print
heal(20, 15),heal(40, 35)andheal(40, 35, 100). The program prints:35 50 75 - 3
Use
filterto keep the potions that heal more than 15, and thenmapto turn each of them into a text like+20 health. Store the result inlabels. Then write a functionprintAllwith a parameterlinesof typestring[]and the return typevoid, which prints each element oflineson its own line, and callprintAll(labels). At the end, the program prints:+20 health +35 health +50 health