我希望能够在泛型中使用联合判别。然而,它似乎并没有起作用:
示例代码(在 TypeScript Playground 上查看):
interface Foo{
type: 'foo';
fooProp: string
}
interface Bar{
type: 'bar'
barProp: number
}
interface GenericThing<T> {
item: T;
}
let func = (genericThing: GenericThing<Foo | Bar>) => {
if (genericThing.item.type === 'foo') {
genericThing.item.fooProp; // this works, but type of genericThing is still GenericThing<Foo | Bar>
let fooThing = genericThing;
fooThing.item.fooProp; //error!
}
}
我希望 TypeScript 能够认识到,由于我在泛型的
item
属性上进行了区分,因此 genericThing
必须是 GenericThing<Foo>
。我猜这可能不受支持?此外,有点奇怪的是,在直接赋值之后,
fooThing.item
失去了它的区分。
fooProp 在类型上不存在...
- NSjonas