Typescript: How do I define interfaces for nested objects?

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;
}

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.


You can want can be achieved using Record type

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


interface Example2 {
   name: string;
   items : Record<string, Item>; 

}

var obj2: Example2 = {
    name: "test",
    items: {
        "a": {
            id: 1,
            size: 10
        },
        "b": {
            id: 2,
            size: 34
        },
        "c": {
            id: 3,
            size: 34
        }
    }
}

You will also get compile time check:

enter image description here