pgsandstrom
pgsandstrom

Reputation: 14399

"Object is possibly undefined" error even after check

I get the error when accessing the length property. I understand that I could solve the problem by only retrieving the object once, and then performing the undefined-check. Or simply add a !. But I want to understand why this is happening, and find out if there is a nicer solution. Here is the contrived example:

type MyMap<K extends string> = { [key in K]: string|undefined }

const getValueLength = (tmp:MyMap<string>, key:string) => {
  return tmp[key] !== undefined && tmp[key].length
}

I'm running typescript 3.3 in strict mode.

Here is a similar question where the problem was that a check was made inside another function, that is not the issue here.

Upvotes: 3

Views: 300

Answers (1)

wormania
wormania

Reputation: 141

Accessing the key is seen as a function call, which could potentially mutate the object/value you're looking at, therefore there is no guarantee that the first and second calls of tmp[key] are finding the same thing.

To avoid this, make sure you're only calling it once:

type MyMap<K extends string> = { [key in K]: string | undefined };

const getValueLength = (tmp: MyMap<string>, key: string) => {
  const str = tmp[key];
  return str !== undefined && str.length;
};

Upvotes: 3

Related Questions