Your First Type Error
In JavaScript, a variable can hold anything, and what it holds can change from a number to a text at any time:
let lives = 3;
console.log("Lives:", lives);
lives = "three";
console.log("Lives:", lives);In the JavaScript course, this program would print Lives: 3 and Lives: three, and nothing would seem wrong. The trouble would come later: as soon as the game calculated with the lives, for example lives - 1, the result would be NaN.
TypeScript doesn't run this program. Instead, it shows an error:
main.ts(3,1): error TS2322: Type 'string' is not assignable to type 'number'.What happened? On line 1, lives got the value 3, a number. From that, TypeScript decided that lives holds numbers: its type is number. From then on, it checks every value that the program stores in lives. On line 3, the program tries to store "three" there, and that's a text. In TypeScript, the type of texts is string, the same name that typeof gives you in JavaScript. The message says exactly this: a value of the type string is not assignable to the type number, so it can't be stored in a variable that holds numbers. The 3 in main.ts(3,1) is the number of the line with the mistake. You'll learn all the parts of the message in the next exercise.
Notice that the program printed nothing, not even Lives: 3 from line 2, although that line is fine. TypeScript checks the whole program before it runs, and if it finds any type error, nothing runs. In JavaScript, most errors appeared only when the program got to them, and what it had printed until then stayed in the output. TypeScript doesn't start the program until all type errors are fixed.
That may seem strict, but it's exactly what makes TypeScript useful. The mistake is reported right away, on the line where it is, and not as a strange NaN somewhere later, or as a wrong result that nobody notices.
A variable keeps its type for the whole program, but its value can change, as long as the new value has the same type: lives = 2; is fine. Careful with quotes, though: lives = "2"; is an error too, because "2" in quotes is a text, not a number.
Instructions
The program in the editor counts Kira's gold and potions in a shop, but TypeScript won't run it. Click Run and read the error message. Then fix the line with the mistake: Kira has bought one more potion, so she now has 3, and potions must remain a number. The program then prints:
Gold: 120 Potions: 2
Gold: 90 Potions: 3Before her next fight, Kira drinks one potion. At the end of the program, lower potions by 1 with potions = potions - 1; and print the same line once more, so that the program prints:
Gold: 120 Potions: 2
Gold: 90 Potions: 3
Gold: 90 Potions: 2Start programming for free
2/7