Type for object with required key value pairs and additionally any other key value pairs

huangapple go评论66阅读模式
英文:

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 = &#39;A&#39;,
    B = &#39;B&#39;,
}

type EnumValue = {
    title: string;
    infoText: string;
};

type RequiredType = Record&lt;MyEnum, EnumValue&gt;;

const myObj = {
    A: { infoText: &#39;a&#39;, title: &#39;a title&#39; },
    B: { infoText: &#39;b&#39;, title: &#39;b title&#39; },
    someOtherKey: &#39;string value&#39;,
};

How to specify the type for myObj so it would be of type Record&lt;MyEnum, EnumValue&gt; as the required type (all enum values should be included as keys) and additionally accept Record&lt;string, string&gt; 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 &amp; Record&lt;string,string&gt;;
     const myObj:myObjType = {A:{infoText:&#39;a&#39;,title:&#39;a title&#39;},
                              B:{infoText:&#39;b&#39;,title:&#39;b title&#39;},
                               someOtherKey:&#39;string value&#39;,};

huangapple
  • 本文由 发表于 2023年4月13日 14:44:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76002384.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定