【发布时间】:2018-11-24 23:52:45
【问题描述】:
我希望能够将union discrimination 与泛型一起使用。但是,它似乎不起作用:
示例代码 (view on 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 失去了它的歧视。
【问题讨论】:
-
最后一行出现什么错误?仅从 genericThing 中提取项目,无论是在函数顶部还是通过在参数中解构,有什么不同吗?
-
@jonrsharpe 打开 typescript playground 链接,您可以看到它。
fooProp does not exist on type ...
标签: typescript discriminated-union