Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: How do I define interfaces for nested objects?

Tags:

typescript

People also ask

How do I define interfaces for nested objects?

To define interfaces for nested objects with TypeScript, we can use index signatures with interfaces. to create the Item interface that we set as the type for any properties in the items object property in the Example interface. Adding [key: string] means that items can have any keys.

How do you define a type for nested object in TypeScript?

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.

What is nested interface in TypeScript?

TypeScript Nested Interface TypeScript allows both type aliases and interface to be nested. An object typed with a nested interface should have all its properties structured the same way as the interface definition.

How would you define interface for array of objects in TypeScript?

To define an interface for an array of objects, define the interface for the type of each object and set the type of the array to be Type[] , e.g. const arr: Employee[] = [] . All of the objects you add to the array have to conform to the type, otherwise the type checker errors out.


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.