Search code examples
javascriptooptypescriptecmascript-6getter-setter

"Instance-wide" getter/setter for TypeScript class?


So I know I can set getters/setters per property.

export class Person {
    private _name: string;

    set name(value) {
        this._name = value;
    }

    get name() {
        return this._name;
    }
}

But is there a way to have a "global instance-wide" setter that trigger whenever any property of a class instance gets modified? Without manually adding a function call in every getter/setter calling that trigger function? Like, something built into TypeScript?

Thanks in advance.


Solution

  • There isn't a built-in way in TypeScript to do this, nor a JavaScript runtime feature for it.

    The closest thing would be a Proxy, which can wrap an underlying object and intercept property assignments. But you'd have to make sure the class instances got wrapped before they were passed off to somewhere else.