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

Typescript: How do I define interfaces for nested objects?

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

Problem

Assume I have a JSON payload that parses into something like this:

{
    name: "test",
    items: {
        "a": {
            id: 1,
            size: 10
        },
        "b": {
            id: 2,
            size: 34
        }
    }
}


How would I set up the definition of the Example interface to model that the value of the items property is an object whose keys are strings and whose values are defined by the Item interface:

export interface Example {
    name: string;
    items: ???;

}

export interface Item {
    id: number;
    size: number;
}

Solution

Typescript allows you to add a type for the object keys using the syntax [key: string].

As stated in the documentation, these are called indexable types:

Indexable types have an index signature that describes the types we can use to index into the object, along with the corresponding return types when indexing.

In your case, you would use the following:

export interface Item {
    id: number;
    size: number;
}

export interface Example {
    name: string;
    items: {
        [key: string]: Item
    };
}


For reference, here is a link to a live example.

Code Snippets

export interface Item {
    id: number;
    size: number;
}

export interface Example {
    name: string;
    items: {
        [key: string]: Item
    };
}

Context

Stack Overflow Q#42216053, score: 293

Revisions (0)

No revisions yet.