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>isHerowith every property optional. It suits changes:function updateHero(hero: Hero, changes: Partial<Hero>): Hero.Omit<Hero, "id">isHerowithoutid, andPick<Hero, "name" | "level">has onlynameandlevel.Pickchecks the names,Omitdoesn't.readonly string[], also writtenReadonlyArray<string>, is an array that can be read but not changed: nopush, nopop, noitems[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, andRecord<Quest["status"], number>has a number for each of them.- In a type,
typeof startingStatsis the type of a variable:type Stats = typeof startingStats;. JavaScript'stypeofin the code gives a text while the program runs. A & Bis an intersection: both types at once, with all the properties of both:type Boss = Monster & { phase: number };.A | Bis 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
7/7