thepaperescape
thepaperescape

Reputation: 85

TypeScript gives 'Object is possibly undefined' error after importing object in React component

I am new to TypeScript and I'm getting 'Object is possibly undefined' errors after importing an object and attempting to iterate over the arrays inside the object.

I attempted to use the non-null assertion operator to no effect.

Here is a code sandbox. I'm not particularly happy with the conditional rendering solution found in App with ComponentWithProps. Is that the best way to do this?

Any and all feedback would be great! Thank you!

Upvotes: 1

Views: 993

Answers (1)

Liad
Liad

Reputation: 844

The object that is possible undefined is not calendar, but it's the result of the find function call, which is either the type of an array element, or undefined as can be seen in typescript 4.3.5 declarations:

find<T>(value: T, ...): T | undefined;

you need to assert that it's not undefined before accessing the name property:

let time = calendar.hours.find((thisHour) => thisHour.number === 2);

if (time !== undefined) {
    time = time.name;
}

or, a more elegant solution, using the || (logical OR) short circuit evaluation provided with a fallback default value:

let time = calendar.hours.find((thisHour) => thisHour.number === 2)?.name || 'fallbackName';

if your fallback is undefined (just like my first solution) then you can just use the ? optional chaining syntax without the rest of the line:

let time = calendar.hours.find((thisHour) => thisHour.number === 2)?.name;

Upvotes: 4

Related Questions