翻译后的内容:颠倒字面记录类型中的键和值

huangapple go评论88阅读模式
英文:

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: &quot;a&quot;, y: &quot;b&quot;, z: &quot;c&quot; };

I wish to be able to write type Flip&lt;X&gt; such that:

type Bar = Flip&lt;Foo&gt;; // should be { a: &quot;x&quot;, b: &quot;y&quot;, c: &quot;z&quot; };

This is purely a play on types -- not on runtime values.

答案1

得分: 2

这可以通过key remapping来实现。

type Flip&lt;T extends Record&lt;any, any&gt;&gt; = {
	 [K in keyof T as T[K]]: K 
}
英文:

This can be done through the use of key remapping.

type Flip&lt;T extends Record&lt;any,any&gt;&gt; = {
	 [K in keyof T as T[K]]: K 
}

huangapple
  • 本文由 发表于 2023年5月18日 12:08:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76277672.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定