Constants and Literal Types
You know from the previous lesson that a constant can't be assigned again: TypeScript reports TS2588 before the program runs. TypeScript also uses this when it infers types. Compare:
let level = 3; // number
const maxLevel = 10; // 10level is created with let, so later it can hold any other number, and its type is number. maxLevel can never change, so TypeScript gives it the most exact type there is: 10. A type like this, which allows just one value, is called a literal type. It's the same with texts: the type of const heroName = "Kira"; is "Kira".
A literal type is still a number or a text: maxLevel + 1 and heroName.length work as usual. You'll notice literal types mostly in error messages:
const gold = 120;
console.log(gold.toUpperCase());main.ts(2,18): error TS2339: Property 'toUpperCase' does not exist on type '120'.Read type '120' as “the number 120”. With texts, the literal type is in double quotes inside the single quotes of the message: '"rain"' means exactly the text rain:
const weather = "rain";
if (weather === "sun") {
console.log("Kira dries her cloak.");
}main.ts(2,5): error TS2367: This comparison appears to be unintentional because the types '"rain"' and '"sun"' have no overlap.weather is a constant with the value "rain", so it can never be "sun", and the condition can never be true. TypeScript points it out. In a real game, the weather would change, so it would be a let, and the comparison would be fine.
You can also write a literal type yourself, as an annotation. The variable may then hold only that one value:
let difficulty: "hard" = "hard";
difficulty = "easy";main.ts(2,1): error TS2322: Type '"easy"' is not assignable to type '"hard"'.A type with a single value isn't very useful on its own. In lesson 5, you'll combine several: "easy" | "normal" | "hard" is a type that allows exactly these three texts, and TypeScript then catches every typo in them.
let or const? As in the JavaScript course: use const for values that don't change, which is most of them, and let only for those that do, such as health, gold or a counter. TypeScript then makes sure of it before the program runs.
Instructions
Kira faces a dragon, but TypeScript reports two errors. Kira's health changes during the fight: fix the program so that it prints:
Ember breathes fire!
Kira's health: 35/50
Ember breathes fire again!
Kira's health: 20/50Now look at the other variables: dragonName and fireDamage never change, so make them constants. maxHealth stays a constant.
Start programming for free
7/9