【发布时间】:2021-01-29 17:20:36
【问题描述】:
这是一些ts代码:
type TopRoomInfoState = {
loaded: false;
loading: boolean;
error: any;
data: null;
} | {
loaded: true;
loading: boolean;
error: any;
data: GetTopRoomInfoRsp;
}
const inititalState: TopRoomInfoState = {
loaded: false,
loading: false,
error: null,
data: null,
};
type Test = typeof inititalState;
// but this `type Test` is merely the literal type of `const inititalState`
// not the whole union TopRoomInfoState ...
为什么 type Test 是联合 TopRoomInfoState 的子集?如何使类型Test是整个联合类型?
【问题讨论】:
-
我猜这是因为它评估
{ loaded: false, loading: false, error: null, data: null, }如果你附加as TopRoomInfoState它会如你所料。 -
是的,使用 as 断言有效。我只想知道内在原理
-
考虑
A= B | C,让a属于A,那么a可以属于B或C。现在将b视为B。将b分配给a。然后是B。证明:typeof b是B,因为a是(===)b=>typeof a是B。或者让typeof a是A然后a === btypeof b必须是A,但b不能是C-> 矛盾。
标签: typescript covariance control-flow contravariance union-types