-
Notifications
You must be signed in to change notification settings - Fork 0
Nested Object types
To understand how nested object types work, let's move back to the snippet of code where the type Person was created:
type Person = {
name: string;
age: number;
isAdult: boolean;
};On that type, let's implement one more property which is related to a person, their address. Well, normally a person address would not be represented by one of the basic types we have mentioned before. This is most of the times, represented by another object, with properties such as: street, zipcode, number, city, among others.
This is then a good opporunity to make use of nested types to implement this address property for Person. This can be done in two different ways:
-
Creating it directly inside the
Persontype, like displayed below:type Person = { name: string; age: number; isAdult: boolean; address: { street: string; city: string; country: string; }; };
-
Creating the custom type Address and making use of this right inside the
PersontypeThis approach is commonly used in situations where a type definition may be necessary into other parts of your code, as well as to provide some extra flexiblity.
type Address = { street: string; city: string; country: string; }; type Person = { name: string; age: number; isAdult: boolean; address: Address; }; type Company = { owner: string; address: Address; };
Those notes were written while watching the tutorial videos while taking the classes from the online course Learn TypeScript on Scrimba.
Because english is not my mother language, they can contain some typos and everything written here is based on my understanding about the discussed topics and may not be 100% accurate.
If you want the full course, support the instructor by buying their course on Scrimba.
- Home
- Introduction
- Introduction to TypeScript
- The Pizza Application
- Move to TypeScript
- Defensive Coding
- Typing variables
- Typing Pizza App: part 1
- Custom types
- Typing Pizza App: part 2
- Nested Object types
- Optional Properties
- Typing Pizza App: part 3
- Array Types
- Typing Pizza App: part 4
- Literal Types
- Unions
- Typing Pizza App: part 5
- Typing Pizza App: part 6
- Typing Pizza App: part 7
- Returning Types
- Typing Pizza App: part 8
- Any Type
- Typing Pizza App: part 9
- Utility Types
- Typing Pizza App: part 10
- Generics
- Typing Pizza App: part 11