gpt4 book ai didi

javascript - Typescript 中的双面字典

转载 作者:行者123 更新时间:2023-12-02 23:35:34 25 4
gpt4 key购买 nike

我需要一本 typescript 的双面词典。使用key获取value,使用value获取key

最简单的方法是将这两个项目存储为键

dict = {"key": "value", "value": "key"}

但我想知道是否还有其他解决方案。

最佳答案

在 JavaScript 中,我建议创建一个将常规字典转换为双面字典的函数:

function doubleDictionary(t) {
var ret = Object.assign({}, t);
for (var k in t) {
ret[t[k]] = k;
}
return ret;
}
var foo = doubleDictionary({ a: "b", c: "d" });
console.log(foo.a); // "b"
console.log(foo.b); // "a"
console.log(foo.c); // "d"
console.log(foo.d); // "c"

在 TypeScript 中,我建议使用相同的函数...但添加签名,以便调用者获得强类型的返回值,如下所示(类型函数的说明是内联的):

// ObjToKeyValue<T> turns an object type into a union of key/value tuples:
// ObjToKeyValue<{a: string, b: number}> becomes ["a", string] | ["b", number]
type ObjToKeyValue<T> =
{ [K in keyof T]: [K, T[K]] }[keyof T];

// KeyValueToObj<T> turns a union of key/value tuples into an object type:
// KeyValueToObj<["a", string] | ["b", number]> becomes {a: string, b: number}
type KeyValueToObj<KV extends [keyof any, any]> =
{ [K in KV[0]]: KV extends [K, infer V] ? V : never };

// ReverseTuple<KV> swaps the keys and values in a union of key/value tuples:
// ReverseTuple<[1, 2] | [3, 4]> becomes [2, 1] | [4, 3]
type ReverseTuple<KV extends [any, any]> =
KV extends [any, any] ? [KV[1], KV[0]] : never;

// ReverseObj<T> takes an object type whose properties are valid keys
// and returns a new object type where the keys and values are swapped:
// ReverseObj<{a: "b", c: "d"}> becomes {b: "a", d: "c"}
type ReverseObj<T extends Record<keyof T, keyof any>> =
KeyValueToObj<ReverseTuple<ObjToKeyValue<T>>>;

// take an object type T and return an object of type T & ReverseObj<T>
// meaning it acts as both a forward and reverse mapping
function doubleDictionary<
S extends keyof any, // infer literals for property values if possible
T extends Record<keyof T, S>
>(t: T) {
const ret = Object.assign({}, t) as T & ReverseObj<T>; // return type
for (let k in t) {
ret[t[k]] = k as any; // need assertion here, compiler can't verify k
}
return ret;
}

现在我们得到了与之前相同的值,但它们在编译时是已知的:

const foo = doubleDictionary({ a: "b", c: "d" });
// const foo: {a: "b", c: "d"} & {b: "a", d: "c"};
console.log(foo.a); // compiler knows it is "b"
console.log(foo.b); // complier knows it is "a"
console.log(foo.c); // compiler knows it is "d"
console.log(foo.d); // compiler knows it is "c"

Link to code

好的,希望有帮助;祝你好运!

关于javascript - Typescript 中的双面字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56300251/

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