In my TypeScript code, I have a function that exhibits the following structure:
const myFunction = () => {
if(!props.object) return;
if (someCondition) {
return randomArray.items.find(item => item.id === props.object.someID)
}
...
}
The variable props.object
is defined as type FooObject | null
, and despite implementing checks, the compiler insists on treating it as potentially null.
I've noticed that this issue only arises within functions embedded in arrays. For instance, consider the below scenario:
const myFunction = () => {
if(!props.object) return;
const foo = props.object.property1;
...
}
Here, using props.object
does not result in the null error, and foo
correctly inherits the type of property1
.
After conducting research, my findings didn't yield any solution besides resorting to the !
operator which ignores checks - an undesirable workaround. Alternatively, repeatedly verifying for null using the &&
or ternary operator whenever props.object
is referenced seems redundant. A singular check at the start of the function should suffice logically. Any guidance provided would be greatly appreciated. Thank you in advance!