Using Items
Items are there to be used: a potion heals Kira, a weapon goes into her hand, and a key opens something. Using an item changes the hero, so the function gets her as a parameter and changes her properties. Objects aren't copied when you pass them to a function, so the changes happen to kira herself.
Where will Kira keep the weapon in her hand? In a new property, weapon. At the start of the adventure, her hand is empty, so the property is optional, as in the lesson on object types: weapon?: Weapon. For example, a ranger and her pet:
type Pet = { name: string; species: string };
interface Ranger {
name: string;
pet?: Pet;
}
function adopt(ranger: Ranger, pet: Pet): string {
ranger.pet = pet;
return `${ranger.name} adopts ${pet.name} the ${pet.species}`;
}
const ema: Ranger = { name: "Ema" };
console.log(ema.pet?.name ?? "no pet");
console.log(adopt(ema, { name: "Shadow", species: "wolf" }));
console.log(ema.pet?.name ?? "no pet");This prints:
no pet
Ema adopts Shadow the wolf
ShadowuseItem is a switch on item.kind, like describeItem, but some of its cases first change the hero and only then return the text:
- The potion adds
item.healto her health. If that's more thanmaxHealth, the health is set tomaxHealth: Kira has 34 health, the potion heals 20, and 54 would be more than her 50. - The weapon goes into her hand:
hero.weapon = item;. That works only insidecase "weapon", where TypeScript knows that the item is aWeapon. Above theswitch, the item could be of any kind, and TypeScript would report:main.ts(46,5): error TS2322: Type 'Item' is not assignable to type 'Weapon | undefined'. Property 'damage' is missing in type 'Key' but required in type 'Weapon'. - The key doesn't change anything; it only returns
Kira opens the crypt.
Write the return type string here too. TypeScript then checks that every case returns a text. And as you'll see in the last step, it also reports a kind of item that has no case, even without the never check: the function would end without returning a text.
In the main program, kira.inventory[0] is the first item (the potion) and kira.inventory[1] the second one (the sword). Kira's name is read-only, but that's fine: useItem only reads it.
Instructions
- 1
Add an optional property
weaponof typeWeapontoHero. - 2
Under
describeItem, write a functionuseItem(hero: Hero, item: Item): stringwith aswitchonitem.kind. For the potion, it returnsKira drinks Healing Potion: health 50/50(the hero's name, the item's name and the new health), for the weaponKira equips Silver Sword, and for the keyKira opens the crypt. - 3
At the end of the main program, Kira uses her first two items: print
useItem(kira, kira.inventory[0])anduseItem(kira, kira.inventory[1]). The program ends like this:- Old Key (opens the crypt) Kira drinks Healing Potion: health 50/50 Kira equips Silver SwordIf Kira has
54/50, the potion healed her above her maximum.