我有两组字符串值,我希望将它们作为常量对象从一组映射到另一组。我想从该映射生成两种类型:一种用于键,一种用于值。
const KeyToVal = {
MyKey1: 'myValue1',
MyKey2: 'myValue2',
};
Run Code Online (Sandbox Code Playgroud)
按键很简单:
type Keys = keyof typeof KeyToVal;
Run Code Online (Sandbox Code Playgroud)
我在获取值的编译时类型时遇到麻烦。我认为也许其中一种会起作用:
type Values = typeof KeyToVal[Keys];
type Values<K> = K extends Keys ? (typeof KeyToVal)[K] : never;
type Prefix<
K extends Keys = Keys,
U extends { [name: string]: K } = { [name: string]: K }
> = {[V in keyof U]: V}[K];
Run Code Online (Sandbox Code Playgroud)
所有这些只是做的Values是string。我还尝试调整了两个答案,以适应如何使用打字稿中的查找来推断类型化的mapValues?,但要么我改写错误,要么答案根本不适合我的情况。