简体   繁体   中英

TypeScript classes and interfaces

I have the following typescript code:-

    export class Parent {
    name: string;
    details: Details = {};
}

export interface Details {
    age?: number;
    address?: Address};
}

export interface Address {
    address1: string;
    address2: string;
}

Then I can reference this code to set some values:-

var myOptions = new HSCIC.Visualisation.Services.Parent();

myOptions.name = "Chris";
myOptions.details.age = 25;
myOptions.details.address.address1 = "10 The Lane";

The first two setters are working fine but I get a 'Cannot set property 'address1' of 'undefined'.

If I can set the age property from Details, then why can't I set the address1 property of Address, and how can I fix it?

Because you wrote:

address?: Address};

But for the code to be valid, it should be:

address?: Address = {address1: null, address2: null};

You need to assign a value to address, just like you did in details: Details = {}; , or it will be undefined. To do it this way, Details would need to be defined as a class, not an interface. Writing : Address does not instantiate a new class, it only specifies the type. Alternatively, you can make address1 and 2 optional like you did address, using ? , and then just write address?: Address = {};

If you don't want to define Details as a class, you could write details: Details = {address:{}}; under Parent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM