英文:
Type for object with required key value pairs and additionally any other key value pairs
问题
You can specify the type for myObj
as follows to meet your requirements:
type MyObj = Record<MyEnum, EnumValue> & Record<string, string>;
const myObj: MyObj = {
A: { infoText: 'a', title: 'a title' },
B: { infoText: 'b', title: 'b title' },
someOtherKey: 'string value',
};
This type definition ensures that myObj
is of type Record<MyEnum, EnumValue>
for enum keys and Record<string, string>
for other keys. Autocompletion for all keys should work as expected with this type definition.
英文:
I am trying to declare an object which should have all keys of MyEnum
with the value of type EnumValue
and any other keys with string
type value. Please see the example below.
enum MyEnum {
A = 'A',
B = 'B',
}
type EnumValue = {
title: string;
infoText: string;
};
type RequiredType = Record<MyEnum, EnumValue>;
const myObj = {
A: { infoText: 'a', title: 'a title' },
B: { infoText: 'b', title: 'b title' },
someOtherKey: 'string value',
};
How to specify the type for myObj
so it would be of type Record<MyEnum, EnumValue>
as the required type (all enum values should be included as keys) and additionally accept Record<string, string>
type?
Edit: also I would like to have autocompletion for all keys in that object. Is it possible by inferring properties from declared myObj
?
答案1
得分: 1
You need to declare myObj as of type myObjType
将myObj声明为myObjType类型
type myObjType = RequiredType & Record<string, string>;
const myObj: myObjType = {
A: { infoText: 'a', title: 'a title' },
B: { infoText: 'b', title: 'b title' },
someOtherKey: 'string value',
};
英文:
You need to declare myObj as of type myObjType
type myObjType = RequiredType & Record<string,string>;
const myObj:myObjType = {A:{infoText:'a',title:'a title'},
B:{infoText:'b',title:'b title'},
someOtherKey:'string value',};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论