Type Annotations

So far, TypeScript has inferred every type from the first value. You can also write the type yourself: after the name of the variable, write a colon and the type:

let heroName: string = "Kira";
let gold: number = 120;
let hasMap: boolean = false;

The part : string is a type annotation. It says what the variable may hold: heroName only texts, gold only numbers, and hasMap only true or false. You can read the first line as “heroName holds a string, and its first value is "Kira"”. Annotations work the same way with const: const maxLevel: number = 10;.

With an annotation, TypeScript checks the first value too, not only the later ones. When the value doesn't fit the type, it reports an error right on the line that creates the variable:

let gold: number = "120";
main.ts(1,5): error TS2322: Type 'string' is not assignable to type 'number'.

Column 5 points at the name of the variable. "120" in quotes is a text, but the annotation says that gold holds numbers. Without the annotation, TypeScript would infer string and report nothing here. The mistake would show up later, on a line that calculates with gold, or perhaps never.

Annotations exist only for the check. As you saw in the previous lesson, the compiler removes them, and the JavaScript that runs is just let gold = 120;.

Typical mistakes:

  • An equals sign instead of a colon: let title = string; tries to store string in the variable as a value, but it's a type, not a value: error TS2693: 'string' only refers to a type, but is being used as a value here.
  • A type that doesn't exist: let level: int = 3; ends with error TS2304: Cannot find name 'int'. Some languages have a special type for whole numbers, but TypeScript has one type for all numbers: number.
  • A capital letter: with a capital, String, Number and Boolean mean something else in TypeScript, the types of special objects that you'll practically never need. TypeScript doesn't report them as an error, so watch out for them yourself: the basic types are written in lowercase.

Instructions

Add type annotations to the three variables in the editor: heroName is a string, level a number and hasMap a boolean.

Below them, create a variable gold with the annotation number and the value 120.

Kira finds a map in a chest. Below the variables, set hasMap to true, and change the console.log at the end so that the program prints:

Kira, level 3, gold 120, map: true

Start programming for free

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

Or sign up with:

1/9