【发布时间】:2019-05-08 18:54:29
【问题描述】:
我有两组字符串值,我想将它们作为常量对象从一组映射到另一组。我想从该映射中生成两种类型:一种用于键,一种用于值。
const KeyToVal = {
MyKey1: 'myValue1',
MyKey2: 'myValue2',
};
按键很简单:
type Keys = keyof typeof KeyToVal;
我在获取值的 编译时 类型时遇到问题。我想也许其中一个会起作用:
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];
所有这些都使Values 成为string。我还尝试将这两个答案改编为How to infer typed mapValues using lookups in typescript?,但要么我的改编错误,要么答案一开始就不适合我的场景。
【问题讨论】:
标签: typescript typescript-typings