Skip to content

Nested Objects in TypeScript

interface Address {
street: string;
city: string;
zipCode: string;
}
interface Employee {
id: number;
name: string;
address: Address;
department: {
id: number;
name: string;
};
}
interface Company {
name: string;
headquarters?: {
address?: {
street?: string;
city?: string;
};
phone?: string;
};
}
function getCity(company: Company): string | undefined {
return company.headquarters?.address?.city;
}
interface TreeNode<T> {
value: T;
children: TreeNode<T>[];
}
interface Comment {
id: string;
text: string;
replies: Comment[];
}

Easy: How do you type nested objects?

Medium: How does optional chaining work with nested types?

Hard: How would you create a recursive type for a tree structure?