In the following example, in the getAdditionalData
function, Typescript infers the type of value
to never
after validating the type through isBarType
. I would expect the type to be FooEntity
since Entity
can be either FooEntity
OR BarEntity
.
Why is that the case?
I’m aware I can avoid the problematic by doing the opposite validation, i.e. if(isFooType(value)) { return value.additionalData;}
but I’m interested to know why Typescript behaves like this.
Link to TS Playground
type BaseEntity = {
id: string,
name: string,
}
type FooEntity = BaseEntity & {
additionalData: string,
}
type BarEntity = BaseEntity & {};
type Entity = FooEntity | BarEntity;
function isFooType(value: Entity): value is FooEntity {
return value.name === 'foo';
}
function isBarType(value: Entity): value is BarEntity {
return value.name === 'bar';
}
function getAdditionalData(value: Entity): string {
if(isBarType(value)) {
return '';
}
// Property 'additionalData' does not exist on type 'never'
return value.additionalData;
}