为什么TypeScript的typeof关键字只获取文字类型?

问题描述

这是一些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的子集?如何使类型测试成为整体联合类型?

enter image description here

解决方法

因为您已经给Typescript提示,TopRoomInfoState变量是构成initialState的类型之一。

如果对象的loaded属性为false,则您的对象属于任一类型

{
  loaded: false;
  loading: boolean;
  error: any;
  data: null;
}

或完全不是TopRoomInfoState类型。如果您的数据属性的类型为GetTopRoomInfoRsp,也是如此,那么您的对象肯定不能为类型

{
  loaded: false;
  loading: boolean;
  error: any;
  data: null;
}

这被称为打字稿中的类型缩小。我建议在TS docsDiscriminating Unions中查找它。