let person = {
// The "name" property is another object
name: {
first: "Joe",
last: "Bloggs"
},
age: 30
};
console.log(person.name.first); // Joe
This allows us to build more complex data structures. Everything can be organised in to properties and sub-properties, instead of having to have lots of properties all on the same object.
TypeScript will also infer a type for the person
variable that describes both the object and any nested objects. The type that is inferred in this case looks like this:
{
name: {
first: string,
last: string
},
age: number
};
That type is getting quite long. If you wanted to declare it explicitly, you could make use of multiple type
declarations which can also be nested, like this:
type NameType = {
first: string,
last: string
};
type PersonType = {
name: NameType,
age: number
};
let person: PersonType = {
name: {
first: "Joe",
last: "Bloggs"
},
age: 30
};