我得到一個說類型爲A
的對象實例。如何在Typescript中使用getter函數來擴展它?添加一個功能我做如何使用get屬性擴展打字稿類?
A.prototype.testFunction = function() {
if(this.something) {
return this.something;
}
return null;
}
我在index.d.ts
文件擴展類型,如:
interface A {
testFunction(): SomeType|null;
}
但我怎麼添加它,如果我想顯示爲一個getter函數,和不只是一個功能?
我試圖尋找在Object.defineProperty()
但打字稿本身似乎並沒有太滿意了一個工作,在下面的代碼指的是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
});
'function()'聲明不會捕獲'this'上下文,但箭頭函數'=>'會。 'testFunction =()=> {do stuff}'[see docs](https://www.typescriptlang.org/docs/handbook/functions.html) – JBC