0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I have made address1 and address2 optional but it's not happy about the line: address?: Address = {};
Perfect, that's it. I didn't want to make it a class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.