Sometimes, we want to define interfaces for nested objects with TypeScript.
In this article, we’ll look at how to define interfaces for nested objects with TypeScript.
How to define interfaces for nested objects with TypeScript?
To define interfaces for nested objects with TypeScript, we can use index signatures with interfaces.
For instance, we write
export interface Item {
id: number;
size: number;
}
export interface Example {
name: string;
items: {
[key: string]: Item;
};
}
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.
And we set the type of them to Item
so they all have the Item
type.
Conclusion
To define interfaces for nested objects with TypeScript, we can use index signatures with interfaces.