Summary

In this lesson, you learned that:

  • TypeScript works out the type of an object from its properties: { name: string; health: number; }. You can't add a property that isn't in the type (Property 'gold' does not exist on type ...), so give an object all its properties when you create it.
  • An object type can be written as an annotation, let target: { name: string; health: number };, or named with a type alias: type Hero = { name: string; health: number };. Then use Hero for variables, parameters, return types and arrays (Hero[]).
  • In an object literal, a missing property gives TS2741 (Property 'price' is missing in type ...), an extra one TS2353, and a typo TS2561 with Did you mean to write 'price'?.
  • An optional property has a question mark, nickname?: string. It may be missing, its type is string | undefined, and it must be checked before use.
  • A readonly property can't be changed after the object is created: Cannot assign to 'name' because it is a read-only property. Unlike const, it protects one property, not a variable.
  • An interface describes an object too: interface Monster { name: string; health: number }. interface Boss extends Monster { phase: number } adds properties, and a Boss can be used wherever a Monster is needed.
  • A property can hold another object: position: Position. Inner types with their own names make the types and error messages shorter.
  • With Item[], every element of the array is checked, and in for...of, every item is an Item.
  • In functions, object types are parameter types (function train(monster: Monster): void) and return types (function createMonster(name: string): Monster). A function that changes a property changes the very object you passed to it, not a copy.

In the next lesson, Unions and Narrowing, you'll meet types that allow several kinds of values, such as string | number, or a target that can be null, and you'll see how TypeScript follows your conditions to know which one you have.

Instructions

Let's practice. Create an interface Quest with a read-only property id (a number), a title (a string), a reward (a number) and an optional note (a string).

Create an array quests of type Quest[] with three quests: id 1, “Wolves in the Woods”, 50 gold; id 2, “The Lost Crown”, 120 gold, with the note "ask the miller"; id 3, “The Goblin Bridge”, 30 gold. Write a function describeQuest that takes a Quest and returns its line; when the quest has a note, the note goes at the end, in parentheses. With a for...of loop, print every quest:

#1 Wolves in the Woods: 50 gold
#2 The Lost Crown: 120 gold (ask the miller)
#3 The Goblin Bridge: 30 gold

Write a function totalReward that takes a Quest[] and returns the sum of the rewards. Print:

Total reward: 200 gold

Start programming for free

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

Or sign up with:

10/10