Summary

In this lesson, you learned that:

  • A type annotation says what a variable may hold: let heroName: string = "Kira";. The basic types are string, number and boolean, in lowercase. With an annotation, TypeScript checks the first value too.
  • When a variable gets a value right away, the inferred type is enough. Write the type where the value doesn't say it: for a variable without a value, an empty array or a tuple.
  • For a variable without a value, let reward: number;, TypeScript checks that every path stores a value before the variable is used. Otherwise, it reports TS2454, often because of a missing else.
  • Arithmetic (-, *, /, %) needs numbers: "15" * 2 is error TS2362. Comparing a number with a text is an error too (TS2367, TS2365). + with a text joins. Number("15") turns a text into a number and String(15) a number into a text.
  • Arrays have types such as string[] and number[]. Pushing a value of another type is error TS2345. An empty array needs its type: const loot: string[] = [];.
  • A tuple, such as [string, number], has a fixed number of elements, each with its own type, in order: const arrows: [string, number] = ["Arrow", 20];.
  • A constant can't be assigned again (TS2588). Its type is a literal type: const maxLevel = 10; has the type 10, while let level = 3; has number. You can also write a literal type as an annotation: let difficulty: "hard" = "hard"; allows only that one value. Use const for values that don't change.
  • any turns the check off, and JavaScript's bugs come back. Avoid it.

In the next lesson, Functions, you'll give types to the parameters and return values of functions, so that TypeScript checks every call: that it gets the right values, the right number of them, and what it gives back.

Instructions

Practice: Kira goes shopping at the market. Below the two lines in the editor, create an empty array cart for the names of the items she buys, and a tuple lantern with the name "Lantern" and the price 30. Give both of them the right types.

Kira buys the lantern. Push its name from the tuple into cart, subtract its price, also from the tuple, from gold, and print the cart and the gold with console.log("Cart:", cart, "Gold:", gold);. The program prints:

Cart: ["Lantern"] Gold: 70

Then she buys a rope, whose price is on Bruno's sign as text, in ropeSign. Push "Rope" into cart, subtract the price of the rope from gold, and print the same line again, so that the program prints:

Cart: ["Lantern"] Gold: 70
Cart: ["Lantern", "Rope"] Gold: 58

Start programming for free

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

Or sign up with:

9/9