【问题标题】:TypeScript: How to convert Record to unionTypeScript:如何将记录转换为联合
【发布时间】:2022-01-18 00:44:06
【问题描述】:

这种类型有可能吗:

type Input = {
    foo: "a" | "b";
    bar: "c" | "d";
};

选择这种类型:

type Output = 
    { key: "foo"; value: "a" | "b"; } | 
    { key: "bar"; value: "c" | "d"; };

?
谢谢!

【问题讨论】:

  • 孔多塞学院! ????

标签: typescript types


【解决方案1】:

是的,您可以使用映射类型来做到这一点。

type TransformInput<T> = {
  [P in keyof T]: { key: P; value: T[P] }; 
}[keyof T];

type Output = TransformInput<Input>

Output 将评估为

type Output = {
    key: "foo";
    value: "a" | "b";
} | {
    key: "bar";
    value: "c" | "d";
}

【讨论】:

  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 2017-02-21
  • 2013-04-18
  • 2021-10-27
  • 2020-10-16
  • 2017-01-01
  • 2023-01-06
  • 1970-01-01
  • 2012-12-31
相关资源
最近更新 更多