The Right Number of Arguments
In JavaScript, you can call a function with fewer arguments than it has parameters, or with more. A parameter without an argument is undefined, and extra arguments are quietly thrown away:
function damage(power, armor) {
return power - armor;
}
console.log(damage(12));
console.log(damage(20, 5, 3));In JavaScript, this prints:
NaN
15NaN (“not a number”) is what you get when you compute with undefined: 12 - undefined. In the second call, the 3 was perhaps meant as a bonus, but damage has no parameter for it, so it's lost without a word.
TypeScript checks the number of arguments in every call. With the types added:
function damage(power: number, armor: number): number {
return power - armor;
}
console.log(damage(12));
console.log(damage(20, 5, 3));main.ts(5,13): error TS2554: Expected 2 arguments, but got 1.
main.ts(6,27): error TS2554: Expected 2 arguments, but got 3.Expected 2 arguments, but got 1: the function has two parameters, so it expects two arguments, and the call passes only one. When an argument is missing, the column points at the function's name. When there's one too many, it points at the first extra argument.
When you see this error, look at the function's first line: what does it need, and in what order? Sometimes the call is wrong, and you fix the call. Sometimes the function really needs another value, and you add a parameter. Then TypeScript does something very useful: it shows you every call in the program that has to change. In a large program, that can be dozens of places, which you'd otherwise have to look for yourself, and in JavaScript, the ones you missed would quietly compute with undefined.
Parameters that may be left out exist too. They're the topic of the next two exercises.
Instructions
Fix both calls. Kira hits the goblin for 8 damage. Bruno's call has one argument too many: remove the 3. The program prints:
Kira hits the goblin for 8 damage
Bruno hits the wolf for 12 damageMonsters now have armor, which lowers the damage. Add a fourth parameter armor of type number to attack. TypeScript then reports both calls, because each of them now lacks an argument. Add the armor to them: the goblin has armor 2, the wolf 5.
Now use the armor: in the returned text, write ${damage - armor} instead of ${damage}. The program prints:
Kira hits the goblin for 6 damage
Bruno hits the wolf for 7 damageStart programming for free
4/10