Type Inference

In the previous exercises, you never told TypeScript that potions holds a number, or that the hero has a property health. TypeScript worked it out by itself, from the values. This is called type inference: TypeScript infers (works out) the type of each variable from the value that you give it.

For simple values, TypeScript has three basic types. Their names are the same as the ones typeof gives you in JavaScript:

  • string: a text, such as "Kira" or "".
  • number: any number, whole or decimal, such as 120, -5 or 2.5. TypeScript has one type for all numbers.
  • boolean: true or false.
let heroName = "Kira"; // string
let gold = 120;        // number
let hasMap = false;    // boolean

TypeScript infers the types of objects and arrays too. For { name: "Kira", health: 50 }, the type is { name: string; health: number; }, as you saw in an error message in the previous exercise. You'll learn more about such types in the next lessons.

The type decides what you may do with a value. A text has a length and can be converted to uppercase; a number has neither:

let heroName = "Kira";
let gold = 120;

console.log(heroName.toUpperCase());
console.log(gold.toUpperCase());
main.ts(5,18): error TS2339: Property 'toUpperCase' does not exist on type 'number'.

toUpperCase() is a method of texts, so TypeScript allows it for heroName, which is a string. For gold, which is a number, it reports that the type number has no such property. (A method is a property whose value is a function, so the message says property.) As JavaScript, this program would print KIRA and then crash with TypeError: gold.toUpperCase is not a function, but only when it got to that line. If the line were inside an if that runs only now and then, the bug could stay hidden for weeks. TypeScript checks every line, including the ones that don't run this time.

One more thing you may notice: with const gold = 120;, the message would name the type '120' instead of 'number'. It's a number too, just an exact one, because a constant never changes. You'll find out more in the next lesson.

Typical mistakes:

  • A method of texts used on a number, as above, often because two variables got mixed up.
  • The length of a number: gold.length gives Property 'length' does not exist on type 'number'. Texts and arrays have a length, numbers don't.

Instructions

The character sheet in the editor should print Kira's class in uppercase, but a variable got mixed up. Run the program, find the mistake from the error message and fix it, so that the program prints:

Name: KIRA
Class: RANGER
Gold: 120

At the end of the program, print the types of the three variables with JavaScript's typeof, in the order heroName, heroClass, gold. They're the same types that TypeScript inferred. The program then also prints:

Types: string string number

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

4/7