gpt4 book ai didi

typescript - 如何获得 TypeScript 映射类型的逆?

转载 作者:行者123 更新时间:2023-12-04 16:41:57 25 4
gpt4 key购买 nike

我正在寻找 TypeScript 映射类型的“逆”(其属性严格是字符串,以便“可逆”)。为了说明我想要的结果,我需要一个通用的 type

type Inverse<M> = ...

能够转换

type MappedType = {
key1: 'value1'
key2: 'value2'
};

进入

/**
* {
* value1: 'key1';
* value2: 'key2';
* }
*/
type MappedTypeInverse = Inverse<MappedType>

我已经尝试了一些东西..但无济于事:

type Inverse<M> = M extends Record<infer O, infer T> ? Record<T, O> : never;

/**
* type MappedTypeInverse = {
* value1: 'key1' | 'key2'
* value2: 'key2' | 'key2'
* }
*/
type MappedTypeInverse = Inverse<MappedType>
type InverseValue<M extends Record<any, any>, V extends M[keyof M]> = V extends M[infer K] ? K : never;

/**
* type MappedTypeInverseValue = unknown // expecting 'key1'
*/
type MappedTypeInverseValue = InverseValue<MappedType, 'value1'>

这可能吗?任何帮助将不胜感激!

最佳答案

这是一个精益alternative (除了帕特里克罗伯特的好解决方案):

type KeyFromVal<T, V> = {
[K in keyof T]: V extends T[K] ? K : never
}[keyof T];

// we assume the type to be an object literal with string values
// , should also work with number or symbol
type Inverse<M extends Record<string, string>> = {
[K in M[keyof M]]: KeyFromVal<M, K>
};

type MappedType = {
key1: 'value1'
key2: 'value2'
};

type MappedTypeInverse = Inverse<MappedType> // { value1: "key1"; value2: "key2"; }

关于typescript - 如何获得 TypeScript 映射类型的逆?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59058685/

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