Typescript: How do I define interfaces for nested objects?

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)