Summary

In this lesson, you learned that:

  • TypeScript is JavaScript with types. Everything from JavaScript works in it and is written the same way; TypeScript adds a check of the types.
  • Before the program runs, the compiler checks it and turns it into JavaScript by removing the types. If it finds any type error, nothing runs, not even the lines before the mistake.
  • TypeScript infers the type of a variable from its value: in let gold = 120;, gold is a number; "Kira" is a string and true a boolean. The variable keeps its type, so gold = "a lot"; is error TS2322.
  • The type decides what you may do with a value: heroName.toUpperCase() is fine, gold.toUpperCase() is error TS2339.
  • An error message such as main.ts(4,29): error TS2551: … gives the file, the line, the column, the error's code and a description in English. Fix the first error first and run the program again. A mistake in how the program is written, such as a missing ), hides the type errors until you fix it.
  • TypeScript catches typos in the names of variables (TS2304, TS2552) and properties (TS2339, TS2551), and it often suggests the right name: Did you mean 'health'? Assigning to a constant is error TS2588, but the properties of an object in a constant may change: hero.health = 40; is fine.
  • When the program runs, the types are gone, and it behaves exactly like JavaScript: "5" + 3 is still "53". Joining a text and a number with + is allowed, but TypeScript won't let the resulting text into a variable for numbers.

In the next lesson, Basic Types, you'll write types yourself. You'll tell TypeScript what a variable may hold, and you'll meet arrays, tuples, constants with exact types, and any, the type that turns the check off.

Instructions

Practice: Kira is shopping at Bruno's. Fix all the errors in the program, so that it prints:

Shop owner: BRUNO
Kira buys a sword. Gold: 75
Kira buys a potion. Gold: 60

Bruno buys a wolf pelt from Kira for 25 gold. At the end of the program, create a constant peltPrice with this price, add it to Kira's gold, and print the result, so that the last line of the output is:

Kira sells a wolf pelt. Gold: 85

Start programming for free

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

Or sign up with:

7/7