Object is possibly undefined in Typescript, even though it's inside an if statement that checks for truthiness

59 Views Asked by At

I received an error in React w/ Typescript says possiblyUndefined is possibly undefined.

So I threw it in an if statement that specifics checks that it's defined before running the function inside the body.

let [state, setState] = useState<{ foo: string }>({ foo: "" });

let possiblyUndefined: { bar: string } | undefined = { bar: "hi" };

useEffect(() => {
  // possiblyUndefined &&
  setState({ foo: possiblyUndefined.bar });
}, []);

But I still get the error.

(Note: I can't do optional chaining because I'm setting this property in a React setState object, and adding optional chaining makes things worse).

Shouldn't Typescript recognize that this function is only going to run if possiblyUndefined ISN'T undefined, therefore it should have no issue with the object property

0

There are 0 best solutions below