Summary

In this lesson, you learned that:

  • Utility types are generic types built into TypeScript that make a new type out of an existing one. They're checked by TypeScript only, and they disappear from the program like every type.
  • Spread (JavaScript) copies the properties of an object into a new object: { ...hero, level: 4 }. What's written later wins, so in { ...hero, ...changes }, the changes replace the old values. In arrays, [...items, "Rope"] makes a new array with one more element.
  • Partial<Hero> is Hero with every property optional. It suits changes: function updateHero(hero: Hero, changes: Partial<Hero>): Hero.
  • Omit<Hero, "id"> is Hero without id, and Pick<Hero, "name" | "level"> has only name and level. Pick checks the names, Omit doesn't.
  • readonly string[], also written ReadonlyArray<string>, is an array that can be read but not changed: no push, no pop, no items[0] = …. A function that only reads an array should take a read-only one; a normal array fits too. Readonly<Hero> makes every property read-only.
  • Hero["heroClass"] is the type of a property of another type, so the type is written only once. On a union, Quest["status"] is the union of all the statuses, and Record<Quest["status"], number> has a number for each of them.
  • In a type, typeof startingStats is the type of a variable: type Stats = typeof startingStats;. JavaScript's typeof in the code gives a text while the program runs.
  • A & B is an intersection: both types at once, with all the properties of both: type Boss = Monster & { phase: number };. A | B is one or the other.

In the next lesson, Final Project, you'll put the whole course together and build Kira's inventory and quest log, step by step.

Now some practice. In the editor, there's Kira's spellbook. Learning a new spell must not change the old book: the function returns a new one.

Instructions

Write a function learnSpell(book: readonly Spell[], spell: Omit<Spell, "id">): Spell[] that returns a new array: all the spells from book, and at the end the new spell with id: book.length + 1. Use spread twice, for the array and for the spell.

Write a function spellsOf(book: readonly Spell[], school: Spell["school"]): string[] that returns the names of the spells of one school, in an array. A for...of loop with push will do, or filter and map.

Under the functions, store learnSpell(spellbook, { name: "Ice Lance", school: "ice", mana: 4 }) in a constant newBook. Then print spellsOf(newBook, "ice") and spellsOf(spellbook, "ice"). The old spellbook hasn't changed:

["Frost Nova", "Ice Lance"]
["Frost Nova"]

Start programming for free

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

Or sign up with:

7/7