Home > Software engineering >  How to make object's key is of type values of an array (values should be optional and not manda
How to make object's key is of type values of an array (values should be optional and not manda

Time:08-21

I am facing a situation where I need to give the object's key is of another array's values, like this

const temp: { [key in typeof someArray[number] ]: string[] } = {
   'animal': ['dog', 'cat']
} // ERROR - missing the following properties from type birds ...  

const someArray = [ 'animals', 'birds' ] as const;  

This makes the temp object should contain keys of all the values inside the array. But, I needed to make the values optional ie., If there is any key then it needs to be one among the values of the array, if some values are not there as keys then there should be no issues

const temp: { [key in typeof someArray[number] ]: string[] } = {
   'animal': ['dog', 'cat']
} // This shouldn't considered as an error 

const temp: { [key in typeof someArray[number] ]: string[] } = {
   'animal': ['dog', 'cat'],
   'random': ['random_1']
} // But this should throw an error

CodePudding user response:

Make the type of temp a Partial:

const temp: Partial<{ [key in typeof someArray[number] ]: string[] }> = {
    'animals': ['dog', 'cat']
}

(btw. 'animals' instead of 'animal')

Partial makes every field optional.

And I recommend using a type instead of an array:

const temp: Partial<{ [key in SomeArray]: string[] }> = {
    'animals': ['dog', 'cat']
}

type SomeArray = 'animals' | 'birds';
  • Related