Summary
In this lesson, you learned that:
- A type annotation says what a variable may hold:
let heroName: string = "Kira";. The basic types arestring,numberandboolean, 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 reportsTS2454, often because of a missingelse. - Arithmetic (
-,*,/,%) needs numbers:"15" * 2is errorTS2362. Comparing a number with a text is an error too (TS2367,TS2365).+with a text joins.Number("15")turns a text into a number andString(15)a number into a text. - Arrays have types such as
string[]andnumber[]. Pushing a value of another type is errorTS2345. 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 type10, whilelet level = 3;hasnumber. You can also write a literal type as an annotation:let difficulty: "hard" = "hard";allows only that one value. Useconstfor values that don't change. anyturns 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
- 1
Practice: Kira goes shopping at the market. Below the two lines in the editor, create an empty array
cartfor the names of the items she buys, and a tuplelanternwith the name"Lantern"and the price30. Give both of them the right types. - 2
Kira buys the lantern. Push its name from the tuple into
cart, subtract its price, also from the tuple, fromgold, and print the cart and the gold withconsole.log("Cart:", cart, "Gold:", gold);. The program prints:Cart: ["Lantern"] Gold: 70 - 3
Then she buys a rope, whose price is on Bruno's sign as text, in
ropeSign. Push"Rope"intocart, subtract the price of the rope fromgold, and print the same line again, so that the program prints:Cart: ["Lantern"] Gold: 70 Cart: ["Lantern", "Rope"] Gold: 58