【问题标题】:Why does type-narrowing fail in this case?为什么在这种情况下类型缩小会失败?
【发布时间】:2018-08-24 05:30:37
【问题描述】:

给定:

export type CommandsTypes = {
  "test-command": {
    propA: string;
    propB: number;
  };

  "test-command2": {
    propC: string;
    propD: number;
  };
};

export type Command<K extends keyof CommandsTypes> = {
  type: K;
  payload: CommandsTypes[K];
};

export type AnyCommand = Command<keyof CommandsTypes>;

为什么以下内容没有按预期缩小类型:

function handle(command: AnyCommand) {
  if (command.type === "test-command") {
    // I would expect the type of command at this point to be
    // Command<"test-command"> 
    // But its not?
  }
}

Typescript 无法将上面的 AnyCommand 类型缩小到的任何想法 Command&lt;"test-command"&gt;?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    Command&lt;keyof CommandTypes&gt; 将等同于{ type: keyof CommandTypes, payload :CommandTypes[keyof CommandTypes] } 基本上这意味着您可以将任何类型与任何有效负载配对,这不是您想要的。

    你会想要建立一个有区别的工会。为此,我们可以使用条件类型的分配行为,它将对键联合的每个成员应用类型转换

    export type AnyCommandHelper<T extends keyof CommandsTypes> =
        T extends keyof CommandsTypes? Command<T>: never
    export type AnyCommand = AnyCommandHelper<keyof CommandsTypes>;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-17
      • 1970-01-01
      • 2014-05-31
      • 2021-10-07
      • 1970-01-01
      相关资源
      最近更新 更多