[SOLVED] Object is possibly undefined when I'm handling those scenarios

Issue

const id = myMap.has(key) ? myMap.get(key) : "defaultValue"

if (id.includes("stuff")) { // Compiler complains saying "Object is possibly undefined"

I don’t understand how this object can ever be undefined. If it has the key, it gets the value. If it doesn’t, the result is "defaultValue". It should cover all cases, why is this complaining?

Solution

It should cover all cases

It doesn’t:

const myMap = new Map<string, any>();
myMap.set("stuff", undefined);
const id = myMap.has(key) ? myMap.get(key) : "defaultValue";
id.includes("default"); // BOOM!

Note that it doesn’t get any better if we avoid any. You could always call it with an unknown string key at runtime, which the compiler knows and it has no way to verify that the accesses are always valid.

Answered By – Jared Smith

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *