HiveBrain v1.2.0
Get Started
← Back to all entries
snippettypescriptCritical

How to define an interface for objects with dynamic keys?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
keysobjectsinterfacedefinedynamicwithforhow

Problem

I have an Object like this that is created by underscore's _.groupBy() method.

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


How would I define that as an Interface with TypeScript?
i don't want to simply define it as myObject:Object = { ... but rather have an own type for it.

Solution

Your object looks like a dictionary of Object arrays

interface Dic {
    [key: string]: Object[]
}


The typescript literature often refers to this pattern as "the description of an indexable object" with a general form

interface Dic {
    [key: string|number]: object_type
}


or

type Dic = {
    [key: string|number]: object_type
}

Code Snippets

interface Dic {
    [key: string]: Object[]
}
interface Dic {
    [key: string|number]: object_type
}
type Dic = {
    [key: string|number]: object_type
}

Context

Stack Overflow Q#39256682, score: 496

Revisions (0)

No revisions yet.