Which Operations Are Allowed
TypeScript knows what each operator does with each type, and it reports the operations that don't make sense. This program has four of them:
let gold = 120;
const priceTag = "15";
console.log(priceTag * 2);
console.log(gold - priceTag);
if (gold === "120") {
console.log("Kira is rich!");
}
if (gold > "100") {
console.log("Kira is rich!");
}main.ts(4,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
main.ts(5,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
main.ts(6,5): error TS2367: This comparison appears to be unintentional because the types 'number' and 'string' have no overlap.
main.ts(9,5): error TS2365: Operator '>' cannot be applied to types 'number' and 'string'.- Arithmetic needs numbers. The operators
-,*,/and%are arithmetic operations, and both of their sides, the left-hand one and the right-hand one, must be numbers. (anyturns the check off, and you'll get to it at the end of this lesson;bigintis a type for huge whole numbers, and enums are an older feature of TypeScript that this course doesn't use.) In JavaScript,"15" * 2is30, because JavaScript turns the text into a number by itself. TypeScript treats it as a mistake: you probably didn't know that the value is a text, and with+, the same value would join instead of add. - A number and a text are never equal.
===compares the types too, so in JavaScript,gold === "120"is alwaysfalse. TypeScript tells you that the comparison looks unintentional, because no value can be a number and a text at once (the types have “no overlap”). Comparing with<or>is an error too. - Joining with
+is allowed. When one side of+is a text,+joins, as you know:"Gold: " + gold.
When a number is stored as text, convert it. Number() from the JavaScript course turns a text into a number, and String() turns a number into a text:
console.log(Number("15") * 2);
console.log(String(15) + 2);This prints:
30
152TypeScript knows that Number(…) is always a number, so Number(priceTag) * 2 is fine. It doesn't know whether the text really contains a number, though: Number("fifteen") gives NaN, as in JavaScript.
Instructions
Kira buys 40 arrows in Bruno's shop, but TypeScript reports two errors. Fix both: turn the price from the price tag into a number with Number(), and compare the gold with the number 50. The program then prints:
Kira is running out of gold!
Gold left: 40Bruno writes Kira a receipt. At the end of the program, print it, joining the texts with count and total using +:
Receipt: 40 arrows for 80 goldStart programming for free
4/9