问题描述
这是一些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的子集?如何使类型测试成为整体联合类型?
解决方法
因为您已经给Typescript提示,TopRoomInfoState
变量是构成initialState
的类型之一。
如果对象的loaded
属性为false
,则您的对象属于任一类型
{
loaded: false;
loading: boolean;
error: any;
data: null;
}
或完全不是TopRoomInfoState
类型。如果您的数据属性的类型为GetTopRoomInfoRsp
,也是如此,那么您的对象肯定不能为类型
{
loaded: false;
loading: boolean;
error: any;
data: null;
}
这被称为打字稿中的类型缩小。我建议在TS docs和Discriminating Unions中查找它。