Lawrence Wagerfield
Lawrence Wagerfield

Reputation: 6611

Define getter/setter on existing object w/ TypeScript

How would I write the following code using TypeScript?

document.__defineGetter__('cookie', function() { ... });
document.__defineSetter__('cookie', function(v) { ... });

Thanks in advance!

(p.s. this assumes document exists, but document.cookie does not... )

Upvotes: 2

Views: 1001

Answers (1)

toskv
toskv

Reputation: 31622

You can use Object.defineProperty in order to do so.

You'll also have to amend the existing's object interface so the compiler knows you added it too.

interface Document {
    cake: string
}

Object.defineProperty(document, 'cake', {
    get: function () {
        return this.id + 'a';
    },
    set: function (value) {
        this.id = value;
    }
});


console.log(document.cake);

document.cake = 'abc';

console.log(document.cake);

You can see a working example here.

Upvotes: 5

Related Questions