简体   繁体   English

为什么在这种情况下类型缩小会失败?

[英]Why does type-narrowing fail in this case?

Given:鉴于:

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>;

Why does the following not type-narrow as expected:为什么以下内容没有按预期缩小类型:

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?
  }
}

Any ideas why Typescript isnt able to narrow the AnyCommand type above to Command<"test-command"> ?任何想法为什么 Typescript 无法将上面的AnyCommand类型缩小到Command<"test-command">

Command<keyof CommandTypes> will be equivalent to { type: keyof CommandTypes, payload :CommandTypes[keyof CommandTypes] } basically this would mean you could pair any type with any payload, which is not what you want. Command<keyof CommandTypes>将等价于{ type: keyof CommandTypes, payload :CommandTypes[keyof CommandTypes] }基本上这意味着你可以将任何类型与任何有效载荷配对,这不是你想要的。

You would want to build a discriminated union.你会想要建立一个受歧视的工会。 Todo this we can use the distributive behavior of conditional types which will apply a type transformation over each member of the union of keys为此,我们可以使用条件类型的分布行为,该行为将对键联合的每个成员应用类型转换

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM