我得到一个具有 say 类型的对象的实例A
。如何在 Typescript 中使用 getter 函数来扩展它?添加我做的功能
A.prototype.testFunction = function () {
if(this.something) {
return this.something;
}
return null;
}
我将类型扩展为index.d.ts
文件如:
interface A {
testFunction (): SomeType|null;
}
但是,如果我想显示为 getter 函数,而不仅仅是函数,我该如何添加它呢?
我试着看看Object.defineProperty()
但 Typescript 本身似乎并不太乐意使用这个,指的是错误的实例this
在下面的代码中:
Object.defineProperty(A.prototype, "testGet", {
get: function () {
if(this.something) { // <== this appears to not refer to type A
return this.something;
}
return null;
},
enumerable: false,
configurable: true
});
getter/setter 可以简单地声明为接口中的属性:
interface A {
testGet: SomeType|null;
}
并指定type of this范围 https://www.typescriptlang.org/docs/handbook/functions.html#this-parametersgetter 函数内部:
Object.defineProperty(A.prototype, "testGet", {
get (this: A) {
if(this.something) {
return this.something;
}
return null;
},
enumerable: false,
configurable: true
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)