Types Disappear
When you click Run, what actually runs isn't TypeScript, but JavaScript. The compiler first checks the types, then it removes them, and the JavaScript that's left runs. Look at this program. The : string and : number after the names of the variables are types written by hand, called type annotations. You'll write them yourself from the next lesson on.
let heroName: string = "Kira";
let arrows: number = 20;
console.log(heroName + " has " + arrows + " arrows.");The compiler turns it into this JavaScript:
let heroName = "Kira";
let arrows = 20;
console.log(heroName + " has " + arrows + " arrows.");Both print:
Kira has 20 arrows.The types are there only for the check. When the program runs, they are gone, and the program does exactly what the same JavaScript would do. TypeScript doesn't change how your code works, so everything you know about JavaScript still holds, its surprises included:
console.log("5" + 3);
console.log(0.1 + 0.2);This prints:
53
0.30000000000000004Why doesn't TypeScript report "5" + 3 as a mistake? Because joining a text and a number with + is valid and very common JavaScript: that's how you build messages such as "Gold: " + gold. TypeScript reports what is almost certainly a mistake, but it doesn't forbid ordinary JavaScript. And 0.30000000000000004 is the tiny inaccuracy of decimal numbers that you know from the JavaScript course. TypeScript can't change that either.
TypeScript does know, though, that "5" + 3 gives a text. So when you try to store such a text in a variable for numbers, it reports an error:
let arrows = 20;
arrows = arrows + "5";main.ts(2,1): error TS2322: Type 'string' is not assignable to type 'number'.Here, the type protects you even from +. But when a variable holds a text from the very start, a text plus a number gives a text again, everything fits, and TypeScript has nothing to report. The program then joins instead of adding, just as JavaScript would. The program in the editor has two bugs like this.
Instructions
- 1
Run the program. It prints
Arrows: 205, and TypeScript reported no error:arrowsholds the text"20", and a text plus a number is a text. Change the first value ofarrowsto a number, so that the program prints:Arrows: 25 - 2
The second bug: after the reward, Kira has
12030gold. Fix it the same way, so that the program prints:Arrows: 25 Gold: 150