使用 TypeScript 在现有对象上定义 getter/setter

Law*_*eld 2 properties typescript typescript2.0

我如何使用 TypeScript 编写以下代码?

document.__defineGetter__('cookie', function() { ... });
document.__defineSetter__('cookie', function(v) { ... });
Run Code Online (Sandbox Code Playgroud)

提前致谢!

(ps这假设document存在,但document.cookie不......)

tos*_*skv 5

您可以使用Object.defineProperty来执行此操作。

您还必须修改现有的对象接口,以便编译器知道您也添加了它。

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);
Run Code Online (Sandbox Code Playgroud)

您可以在此处查看一个工作示例。