[英]TypeScript type that enforces only the properties of an object
Suppose I have the following:假设我有以下内容:
const myObj = { foo: 'cat', bar: 'dog', baz: 'bird' } as const;
type MyValue = 'fish' | 'bear' | 'cow';
const myValueMap: Record<string, MyValue> = {
[myObj.foo]: 'fish',
[myObj.bar]: 'cow',
} as const;
Because myValueMap
is declared as an object with arbitrary string keys, we don't get type-checking on the actual keys of the object ( cat
and dog
).因为
myValueMap
被声明为带有任意字符串键的 object,所以我们不会对dog
cat
的实际键进行类型检查。 I could remove the explicit declaration altogether, but then I don't enforce that the values are MyValue
s.我可以完全删除显式声明,但是我不强制这些值是
MyValue
。 (In my actual code, MyValue
is several hundred constants strings.) (在我的实际代码中,
MyValue
是数百个常量字符串。)
Is there a way, preferably without using a wrapper function, to enforce that values are MyValue
s and still maintain the property type-checking?有没有办法,最好不使用包装器 function,强制值是
MyValue
并且仍然保持属性类型检查?
Maybe make use of more generics -也许使用更多的 generics -
const myValueMap: Record<myObj[keyof myObj], MyValue> = {
[myObj.foo]: 'fish',
[myObj.bar]: 'cow',
};
If I understood you correctly, that's how you can achieve what you require:如果我对您的理解正确,这就是您可以实现所需的方法:
const myObj = { foo: 'cat', bar: 'dog', baz: 'bird' } as const;
type MyValue = 'fish' | 'bear' | 'cow';
const myObjValue = myObj["" as keyof typeof myObj];
const myMap: Partial<Record<typeof myObjValue, MyValue>> = {
[myObj.foo]: 'fish',
[myObj.bar]: 'cow',
} as const;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.