TypeScript:如何将 Record 转换为 union
TypeScript: How to convert Record to union
是否可以从这种类型:
type Input = {
foo: "a" | "b";
bar: "c" | "d";
};
选择此类型:
type Output =
{ key: "foo"; value: "a" | "b"; } |
{ key: "bar"; value: "c" | "d"; };
?
谢谢!
是的,您可以使用映射类型来做到这一点。
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";
}
是否可以从这种类型:
type Input = {
foo: "a" | "b";
bar: "c" | "d";
};
选择此类型:
type Output =
{ key: "foo"; value: "a" | "b"; } |
{ key: "bar"; value: "c" | "d"; };
?
谢谢!
是的,您可以使用映射类型来做到这一点。
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";
}