TypeScriptLesson 2 of 16

Basic types and annotations

The three main primitives are string, number and boolean. Often you can skip the annotation: TypeScript infers the type from the value.

Key points

  • string is text, number is any number, whole or decimal, boolean is true or false.
  • Inference: let city = "Dubai" already has the type string.
  • any switches checking off, so use it as rarely as possible.
  • unknown is the safe version of any: check the value before using it.
  • In strict mode null and undefined are separate types and cannot stand in for a string.

Example

let city = "Dubai"; // inferred as stringlet temperature: number = 31;const isSunny: boolean = true; temperature = 29; // fine: still a number// city = 42;     // error: number is not assignable to string let input: unknown = "42";if (typeof input === "string") {  input = Number(input); // inside the check TypeScript knows it is a string} console.log(`${city}: ${temperature}°C, sunny: ${isSunny}, input: ${input}`);

city has no annotation, but TypeScript inferred string, so assigning 42 is an error. The unknown value input can only be used after a typeof check.

Task

How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.

Annotate the four constants, calculate total = price * quantity and print two lines: "Notebook x3 = 13.5" and "In stock: true".

Output

What your program prints appears here.