相关疑难解决方法(0)

来自Typescript中对象的键和值的类型

我有两组字符串值,我希望将它们作为常量对象从一组映射到另一组。我想从该映射生成两种类型:一种用于键,一种用于值。

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)

所有这些只是做的Valuesstring。我还尝试调整了两个答案,以适应如何使用打字稿中的查找来推断类型化的mapValues?,但要么我改写错误,要么答案根本不适合我的情况。

typescript typescript-typings

7
推荐指数
4
解决办法
3127
查看次数

标签 统计

typescript ×1

typescript-typings ×1