Type Annotations With Objects
Type annotations with objects in TypeScript allow you to specify the types of properties that an object should have.
let personExOne: {
name: string;
age: number;
jobTitle?: string;
address: {
street: string;
city: string;
};
};
personExOne = {
name: "Alice",
age: 30,
jobTitle: "Engineer",
address: {
street: "123 Main St",
city: "Wonderland",
},
};And there is yet another method
// Define an object type with type annotations
let personExTwo: {
name: string;
age: number;
jobTitle?: string;
address: {
street: string;
city: string;
};
} = {
name: "Alice",
age: 30,
jobTitle: "Engineer",
address: {
street: "123 Main St",
city: "Wonderland",
},
};we’re defining an object named personExTwo with specific type annotations for its properties:
nameis a required string property for the person’s name.ageis a required number property for the person’s age.jobTitleis an optional string property for the person’s job title, indicated byjobTitle?: string.addressis an object with two required properties:street(string) andcity(string).
We initialize personExTwo with specific values for each property. Later in the code, we modify some properties. Finally, we use console.log to display the property values of personExTwo.