In this tutorial, I will explain how to declare and use TypeScript interfaces with nested arrays of objects. As a TypeScript developer, you should understand that how to work with nested structures is crucial for building complex applications, especially when dealing with data from APIs or databases.
What is a TypeScript Interface?
A TypeScript interface is a way to define the structure of an object. It ensures that the object adheres to a specific shape, which can include properties, methods, and nested objects. Interfaces are a powerful feature in TypeScript, providing type safety and improving code readability.
Declare a Basic Interface
Let’s start with a simple example. Suppose we have an interface for a Person
object:
interface Person {
firstName: string;
lastName: string;
age: number;
}
This interface defines a Person
with three properties: firstName
, lastName
, and age
.
Check out How to Use TypeScript Interface Function Properties?
Nested Arrays of Objects
Now, let’s move on to a more complex scenario where we have a nested array of objects. Consider an example where each Person
has a list of Address
objects. Here’s how we can define this using TypeScript interfaces:
interface Address {
street: string;
city: string;
state: string;
zipCode: string;
}
interface Person {
firstName: string;
lastName: string;
age: number;
addresses: Address[];
}
In this example, the Person
interface includes an addresses
property, which is an array of Address
objects. Each Address
object has properties for street
, city
, state
, and zipCode
.
Read Define and Use TypeScript Interface Array of Objects
Example with Nested Arrays of Objects
To make this more concrete, let’s consider a scenario where we have a list of people, and each person has multiple addresses. Here’s how you can create and use these interfaces in TypeScript:
const people: Person[] = [
{
firstName: "John",
lastName: "Doe",
age: 30,
addresses: [
{
street: "123 Main St",
city: "Springfield",
state: "IL",
zipCode: "62701"
},
{
street: "456 Elm St",
city: "Chicago",
state: "IL",
zipCode: "60601"
}
]
},
{
firstName: "Jane",
lastName: "Smith",
age: 25,
addresses: [
{
street: "789 Maple Ave",
city: "Los Angeles",
state: "CA",
zipCode: "90001"
}
]
}
];
In this example, people
is an array of Person
objects. Each Person
has a firstName
, lastName
, age
, and an array of Address
objects. This structure allows you to represent complex data relationships in a type-safe manner.
Conclusion
In this tutorial, we explored how to declare and use TypeScript interfaces with nested arrays of objects.
You may also like:
I’m Bijay Kumar Sahoo, and I am honored to be awarded the Microsoft MVP. With over 18 years of experience in the IT industry, I got a chance to work on SharePoint Framework (SPFx) development, TypeScript, React, JavaScript, etc. My journey has taken me through esteemed organizations such as TCS, HP, and KPIT, where I have honed my skills and expanded my expertise. Check out more about me here.