When to Write a Type
Now you can write a type for every variable. Should you? For TypeScript, let gold: number = 120; and let gold = 120; mean the same thing: in both, gold is a number, and gold = "a lot"; is an error. The annotation only repeats what the value 120 already says. That's why programmers usually leave it out when a variable gets its value right away, and let TypeScript infer the type. The code is shorter and easier to read, and when you change the value, you don't have to change the type with it.
Write the type yourself where the value doesn't tell TypeScript what you mean. The most common case is a variable that doesn't have a value yet. Without a type and without a value, TypeScript lets you store anything in it, just like JavaScript:
let reward;
reward = 50;
reward = "fifty";
console.log(reward);This program runs without an error and prints fifty. TypeScript only keeps track of what you store there. With a type, it checks every value you store:
let reward: number;
reward = 50;
reward = "fifty";main.ts(3,1): error TS2322: Type 'string' is not assignable to type 'number'.Without the type, a mistake like this shows up only later, where the program uses the variable, and the message is harder to understand. Say reward gets a number in one branch of an if and a text in the other. Then gold + reward reports Operator '+' cannot be applied to types 'number' and 'string | number'. TypeScript knows that reward may be a text or a number (that's what string | number means; you'll learn more in lesson 5), but it doesn't tell you which line stored the text. With let reward: number;, the error is on the line with the mistake.
Other places where a type is needed, which you'll meet soon:
- An empty array: from
[]alone, TypeScript can't tell what will go in. You'll writeconst loot: string[] = [];in the exercise on arrays. - The parameters of functions: TypeScript can't infer them, so you'll write their types in lesson 3.
- A variable that should hold more than its first value suggests, for example a number or a text (lesson 5).
In this course, we write a type where it's needed or where it makes the code clearer, and elsewhere we let TypeScript infer it.
Instructions
Run the program. TypeScript reports an error on the line that adds the reward to the gold, but the real mistake is elsewhere. Give reward the type number and run the program again. Now the error points at the line that stores a text in reward. A weak monster gives 20 gold: fix the line so that it stores the number 20.
Remove the annotations of heroName, gold and monsterLevel: TypeScript infers the same types from their values. The program still prints Kira has 140 gold.
Kira defeats a stronger monster: change the value of monsterLevel to 6, so that the program prints:
Kira has 220 gold.Start programming for free
2/9