Objects within objects in TypeScript
Objects can contain other objects described by separate interfaces. Let's look at examples.
Let's say we have an interface that describes an object with a city:
interface City {
name: string
}
Let's also make an interface that describes the user. The user will have a name, age, and city, which in turn is an object:
interface User {
name: string,
age: number,
city: City
}
Let's create an object with a user:
let city: City = {name: 'london'};
let user: User = {name: 'john', age: 30, city: city};
It is not necessary to create a separate variable for the city:
let user: User = {
name: 'john',
age: 30,
city: {name: 'london'}
};
Given object:
let employee {
name: 'andrew',
potision: {
name: 'programmer'
salary: 1000,
},
addr: {
country: 'belarus',
city: 'minsk'
}
};
Create an interface that describes the structure of this object. Move nested objects into separate interfaces.
Given object:
let user: User = {
name: 'john',
age: 30,
parents: {
mother: {
name: 'jane',
age: 30,
parents: null
},
father: {
name: 'eric',
age: 30,
parents: null
}
}
}
Create an interface that describes the structure of this object. Move nested objects into separate interfaces.