Why can’t I use optional chaining to test 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})
It transpiles fine, works as designed, and throws no runtime errors.
The property check logically it narrows the scope to {a:number}
.
So… What’s wrong with this?
Is there a setting I can change to make it allow and use this method of type narrowing?
Someone will probably tell me to use the in
operator. So I suppose I’ll say now that I know I could use the in
operator, but I don’t want to. If I union the type with string as well, then I can’t use in
with string and I have to first check to make sure it’s not a string with if(typeof value != 'string')
, but in regular JavasScript I could simply leave my property check with optional chaining and know that whatever I get will have the property and all will be well.
So, what’s the problem with typescript here? Is it just not smart enough to figure it out?