Home > Blockchain >  Object is possibly undefined when I'm handling those scenarios
Object is possibly undefined when I'm handling those scenarios

Time:03-22

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?

CodePudding user response:

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.

CodePudding user response:

If "myMap" was null or undefined, id would be undefined/null as well.

  • Related