When I'm checking if object is declared directly it works just fine obviously, but I'm wondering if it's possible to extract this check into a variable and make TypeScript to still understand it.
import React from "react";
interface Props {
obj?: {
val: string;
}
}
function A({ obj }: Props) {
const hasObj = !!obj;
return (
<>
<p>This works fine:</p>
<div>{!!obj && obj.val}</div>
<p>This throws an error (Object is possibly 'undefined'):
<div>{hasObj && obj.val}</div>
</>
)
}
Is it possible to make it work that way?
<div>{obj?.val}</div>?