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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With