【问题标题】:why TypeScript's typeof keyword just get the literal type?为什么 TypeScript 的 typeof 关键字只是获取文字类型?
【发布时间】: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 可以属于BC。现在将b 视为B。将b 分配给a。然后是B。证明:typeof bB,因为 a 是(===)b => typeof aB。或者让typeof aA 然后a === b typeof b 必须是A,但b 不能是C -> 矛盾。

标签: typescript covariance control-flow contravariance union-types


【解决方案1】:

因为您已向 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 中查找。

【讨论】:

    猜你喜欢
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-30
    • 2022-07-21
    • 2020-12-24
    • 1970-01-01
    • 2019-06-17
    相关资源
    最近更新 更多