【发布时间】:2018-07-18 03:35:48
【问题描述】:
这在 asd 和 sdf 函数中给出了变量 o 的类型与初始化不兼容的错误:
enum E {
a,b,c,d
}
type Xe = E.a | E.b;
type Ye = E.c | E.d;
interface X {
f: Xe;
}
interface Y {
f: Ye;
}
type I = X | Y;
function asd(v: E) {
// Error
const o: I = {
f: v,
};
}
function sdf(o: I) {
if (o.f == E.a) {
// type of o should be narrowed down to X
}
}
错误是:
Type '{ f: E; }' is not assignable to type 'I'.
Type '{ f: E; }' is not assignable to type 'Y'.
Types of property 'f' are incompatible.
Type 'E' is not assignable to type 'Ye'.
由于某种原因,类型 I 不等价于这个接口:
interface I {
f: Xe | Ye;
}
我希望能够在条件中初始化和缩小类型。但是如果我不使用联合类型,缩小类型就不起作用了。
【问题讨论】:
-
问题到底是什么?
-
不,union 不合并内部字段类型,所以
I等价于{ f: Xe } | { f: Ye } -
如果不合并内部字段,也许我想要实现的目标是不可能的,谢谢
标签: typescript