Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complex Typescript Interface with Objects

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?

like image 431
user10181542 Avatar asked Aug 14 '18 04:08

user10181542


People also ask

Are interfaces objects TypeScript?

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.

How do you interface an array of objects in TypeScript?

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!

Can an object have an interface type?

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.

How do you define a type of nested object in TypeScript?

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.


1 Answers

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);
}
like image 131
jh314 Avatar answered Sep 18 '22 03:09

jh314