Learn TypeScript in Construct, part 8: Objects

UpvoteUpvote 3 DownvoteDownvote

Index

Features on these Courses

Stats

132 visits, 153 views

Tools

Translations

This tutorial hasn't been translated.

License

This tutorial is licensed under CC BY-NC 4.0. Please refer to the license text if you wish to reuse, share or remix the content contained within this tutorial.

Published on 11 Jul, 2025.

Nested objects

Remember that objects can be used anywhere other values like numbers and strings can be used. This also applies to object properties, which can also have a value which is another object. Then these properties can be accessed with another dot, or with a chain of square brackets when using string syntax.

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
};
  • 0 Comments

Want to leave a comment? Login or Register an account!