英文:
flip keys and values from a literal record type
问题
在 TypeScript 中,给定一个记录文字,如何交换键和值?
type Foo = { x: "a", y: "b", z: "c" };
我希望能够编写 type Flip<X>
,使其如下所示:
type Bar = Flip<Foo>; // 应该得到 { a: "x", b: "y", c: "z" };
这仅仅是一种对类型的操作,不涉及运行时的值。
英文:
In typescript, given a record literal, how do I switch the keys with the values?
That is:
type Foo = { x: "a", y: "b", z: "c" };
I wish to be able to write type Flip<X>
such that:
type Bar = Flip<Foo>; // should be { a: "x", b: "y", c: "z" };
This is purely a play on types -- not on runtime values.
答案1
得分: 2
这可以通过key remapping来实现。
type Flip<T extends Record<any, any>> = {
[K in keyof T as T[K]]: K
}
英文:
This can be done through the use of key remapping.
type Flip<T extends Record<any,any>> = {
[K in keyof T as T[K]]: K
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论