Start learning free

LESSON 130 OF 675 · DICTIONARIES

Reading a Key That May Be Missing in TypeScript

Lesson

TL ; DR:

Start with the default. Then an if with in replaces it with the value, when the key is there.


const points: { [key: string]: number } = {"Ana": 7};

let score: number = 0;
if ("Ben" in points) {
    score = points["Ben"];
}
console.log(score);   // 0


Full lesson:

A missing key often means "none yet". A player with no points yet has 0 points.

points["Ben"] doesn't stop the program. It gives undefined, not 0.

Then points["Ben"] + 1 is NaN, "not a number".

So start score at the default. The if changes it only when "Ben" is a key.

The type says number. Still, a missing key gives undefined when the program runs.

Reading this way doesn't add the key. points still has one key afterwards.

With "Ana", the same code gives 7.


Your task

stock counts the fruit in a shop. The code reads and prints the pears.

There are no plums yet. Declare plums at 0. Then use an if with in to read stock["plums"] when the key is there.

Then log the plums line, the same way as the pears line.

Expected output:

We have 2 pears
We have 0 plums
STEP 1 OF 3
    Ctrl + Enter to check