Why does TypeScript give an error when using property checking to narrow the type like this?
function test2(value:{a:number}|{b:number}){
// `.a` underlined with: "Property a does not exist on type {b:number}"
if(value.a != null){
console.log('value of a:',value.a)
}
}
test2({a:1})
test2({b:2})
The transpilation is successful, it functions correctly, and there are no runtime errors. The property check logically restricts the scope to {a:number}
.
So what's the issue here? Is there a configuration I can modify in order to allow and use this method for type narrowing?
Someone might suggest using the in
operator. However, I am aware that I could use the in
operator, but I prefer not to. If I include a string in the union type as well, then I cannot use in
with a string directly. I would need to first check that it's not a string with if(typeof value != 'string')
. In regular JavaScript, I could simply rely on my property check and be confident that any value retrieved will have the property, ensuring everything works smoothly.
Therefore, why does TypeScript struggle with this scenario? Is it simply not intelligent enough to handle it?
(Changes: Originally, this question involved optional chaining to check for properties due to the type being unioned with null. To simplify, I've removed both the null and the optional chain operator from the if statement.)