你需要使用
as const
子句并反转对象,如下所示:
https://tsplay.dev/mbaX2N
非PropertyKey(string|number)值是否需要大小写?
const map = {
0: 'a',
1: 'b',
2: 'c',
3: 'd',
} as const
// ^^^^^^^
// const map: {
// readonly 0: "a";
// readonly 1: "b";
// readonly 2: "c";
// readonly 3: "d";
// }
type ValueOf<T> = T[keyof T]
type MapKey = keyof typeof map;
// ^?
// type MapKey = 0 | 1 | 2 | 3
type MapValue = ValueOf<typeof map>
// ^?
// type MapValue = "a" | "b" | "c" | "d"
type Reverse<T extends Record<PropertyKey, PropertyKey>> = {
[K in keyof T as T[K]]: K
}
type ReversedMap = Reverse<typeof map>
// type ReversedMap = {
// readonly a: 0;
// readonly b: 1;
// readonly c: 2;
// readonly d: 3;
// }
function getKey<V extends ValueOf<typeof map>>(value: V): ReversedMap[V] {
return Object.entries(map).find(([k, v]) => v === value)![0] as any
}
let a = getKey('a')
// ^?
// let a: 0