The Report

At the end of the adventure comes a report: how many quests are done, open and failed, and Kira's gold, with the rewards from the done quests added.

For counting, you need a number for every status: an object with one key per status, which is what Record from the lesson on modeling data is for. And you don't have to write the statuses again: Quest["status"] from the previous lesson is the union of all of them. For example, monsters in a cave, counted by their kind:

type Monster = { kind: "goblin" | "wolf" | "troll"; name: string };

const cave: Monster[] = [
    { kind: "goblin", name: "Grub" },
    { kind: "wolf", name: "Grey" },
    { kind: "goblin", name: "Snag" },
];

const counts: Record<Monster["kind"], number> = { goblin: 0, wolf: 0, troll: 0 };
for (const monster of cave) {
    counts[monster.kind]++;
}
console.log(counts);
console.log(`Goblins: ${counts.goblin}`);

This prints:

{ goblin: 2, wolf: 1, troll: 0 }
Goblins: 2

counts[monster.kind] uses the kind as the key, so each monster adds one to its own count. TypeScript checks that the object has every key. In your program, without failed: 0, you'd get main.ts(122,7): error TS2741: Property 'failed' is missing in type '{ open: number; done: number; }' but required in type 'Record<"done" | "failed" | "open", number>'. And if a new status is ever added to Quest, TypeScript reports this object too.

Now the gold. Only a done quest has a reward, so reading quest.reward without a check is an error:

main.ts(126,35): error TS2339: Property 'reward' does not exist on type 'Quest'.
  Property 'reward' does not exist on type '{ status: "open"; title: string; }'.

Inside if (quest.status === "done"), TypeScript narrows the quest to a done one, and quest.reward is fine. Kira is in a const, but you can still change her gold: const only means that the variable always holds the same object.

Instructions

In the main program, above the loop over the quests, create a constant counts of type Record<Quest["status"], number> with a 0 for each status.

In the loop, add one to the count of each quest's status. After the loop, print the counts:

Done: 2, open: 1, failed: 1

In the same loop, add the reward of each done quest to Kira's gold. At the very end, print the line about Kira once more. The program ends like this:

Done: 2, open: 1, failed: 1
Kira the ranger, level 3, health 50/50, gold 200

Kira has her health from the potion and her gold from two quests. If she still has 120 gold, you're printing her before the loop.

Start programming for free

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

Or sign up with:

6/7