ECMAScript 2015/TypeScript 2 setter with objects

109 Views Asked by At

How can I set objects in a class?

interface IAddress {
    streetAddress: string;
    postCode: string;
    city: string;
}

class C {
    private _data = <any> {};

    public get postAddress(): IAddress {
        return this._data.postAddress;
    }

    /*
    public set postAddress() {

    }
    */
}

let a = new C();

Now, when I get that address I have:

let address = a.postAddress;

/*
{
    streetAddress: "";
    postCode: "";
    city: "";
}
*/

Then I want to set some properties via setter (which I can't; don't know how to):

a.postAddress.city = 'NEW YORK';

But nothing happens as a.postAddress first gets the object and C class' setter will never be called. How to achieve this?

1

There are 1 best solutions below

0
On

You need to make the postAddress getter return an object that implements the IAddress interface and has setters for streetAddress, postCode and city.