0

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?

Andyally
  • 863
  • 1
  • 9
  • 22
  • There is no specific type that works this way, see https://stackoverflow.com/q/61431397/2887218 . You can make a generic type and a helper function [as shown here](https://tsplay.dev/mZZBem) instead. Does that meet your needs? If so I'll write up an answer explaining; if not, what am I missing? – jcalz Apr 13 '23 at 22:25

1 Answers1

1

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',};
    
Sweety SK
  • 351
  • 1
  • 10
  • This allows to add string key value pairs alongside required type, but would it be possible also to infer all properties from declared myObj so I can have autocompletion (when accessing myObj properties) as now only properties from RequiredType are show, – Andyally Apr 13 '23 at 08:44