I have an interface defined as:
export interface Address {
addressType: {
house?: {
streetAddress: string,
city: string,
zip: string,
},
apartment?: {
streetAddress: "",
unitNumber: "",
city: "",
zip: "",
buildingName?: "",
},
}
instructions?: string;
}
Then in my Typescript file of my component, I am defining a house address:
address: Address;
constructor() {
this.address.addressType = {
house: {
streetAddress: "1 test",
city: "test city",
zip: "92222",
}
}
console.log(this.address);
}
Though when I log the address to the console, I get:
Uncaught (in promise): TypeError: Cannot set property 'addressType' of undefined
I thought I was setting the addressType in the constructor. Is there a more efficient way to do what I'm doing?
TypeScript Interface Define Objects Only In TypeScript, type aliases can define composite types such as objects and unions as well as primitive types such as numbers and strings; interface, however, can only define objects. Interface is useful in typing objects written for object-oriented programs.
To define an interface for an array of objects, define the interface for the type of each object and set the type of the array to be Type[] , e.g. const arr: Employee[] = [] . All of the objects you add to the array have to conform to the type, otherwise the type checker errors out. Copied!
Therefore, objects can have multiple types: the type of their own class and the types of all the interfaces that they implement. This means that if a variable is declared to be the type of an interface, its value can reference any object that is instantiated from any class that implements the interface.
Use an interface or a type alias to type a nested object in TypeScript. You can set properties on the interface that point to nested objects. The type of the object can have as deeply nested properties as necessary.
You need to initialize this.address
before you can set its addressType:
constructor() {
this.address = {
addressType: {
house: {
streetAddress: "1 test",
city: "test city",
zip: "92222",
}
}
};
console.log(this.address);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With