我有两组字符串值,我希望将它们作为常量对象从一组映射到另一组。我想从该映射生成两种类型:一种用于键,一种用于值。
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
。我还尝试调整了两个答案,以适应如何使用打字稿中的查找来推断类型化的mapValues?,但要么我改写错误,要么答案根本不适合我的情况。
编译器会将字符串文字类型扩展为string
,除非满足某些特定条件,如github issue和PR中所述,或者将const断言用于文字值。Const断言出现在TypeScript 3.4中:
const KeyToVal = {
MyKey1: 'myValue1',
MyKey2: 'myValue2',
} as const;
type Keys = keyof typeof KeyToVal;
type Values = typeof KeyToVal[Keys]; // "myValue1" | "myValue2"
在3.4之前,有一种变通办法可以达到相同的效果。为了使编译器推断文字类型,您必须通过具有适当设计的泛型类型参数的函数传递对象,这种情况似乎可以解决这种情况:
function t<V extends string, T extends {[key in string]: V}>(o: T): T {return o}
该功能的全部目的是捕获和保留类型以启用类型推断,否则它完全没有用,但是有了它,您可以拥有
const KeyToVal = t({
MyKey1: 'myValue1',
MyKey2: 'myValue2',
});
type Keys = keyof typeof KeyToVal;
type Values = typeof KeyToVal[Keys]; // "myValue1" | "myValue2"
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句