gpt4 book ai didi

TypeScript:将键值类型反向映射到值键

转载 作者:行者123 更新时间:2023-12-04 10:22:46 24 4
gpt4 key购买 nike

给定一个类型的对象:

type Key2Value = {
foo: "bar"
voo: "doo"
}

假设该类型的值始终为字符串类型,如何构造实用类型ReverseMap<T>反向映射键值对到值键对?

type Value2Key = ReverseMap<Key2Value>
// yields:
type Value2Key = {
bar: "foo"
doo: "voo"
}

最佳答案

type Key2Value = {
foo: "bar"
voo: "doo"
}

type ReverseMap<T extends Record<keyof T, keyof any>> = {
[P in T[keyof T]]: {
[K in keyof T]: T[K] extends P ? K : never
}[keyof T]
}

type Value2Key = ReverseMap<Key2Value>

Playground

关于TypeScript:将键值类型反向映射到值键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60768302/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com