Interface for dynamic key in typescript

I have an object that is created using the _.groupBy() underscore method.

 myObject = { "key" : [{Object},{Object2},{Object3}], "key2" : [{Object4},{Object5},{Object6}], ... } 

How can I define this as an interface with TypeScript? I don’t want to just define it as myObject:Object = { ... , but rather have my own type for it.

+17
source share
3 answers

Your object looks like a dictionary of Object arrays

 interface Dic { [key: string]: Object[] } 
+54
source

TypeScript now has a dedicated Record type:

 const myObject: Record<string, object[]> = { ... } 

Also, consider key entry if possible:

 type MyKey = 'key1' | 'key2' | ... const myObject: Record<MyKey, object[]> = { ... } 
+10
source

You can also use type:

 type Dic = { [key in string]: Object[] } 
0
source

All Articles