2017-09-01 45 views
2

我得到一個說類型爲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 
}); 
+0

'function()'聲明不會捕獲'this'上下文,但箭頭函數'=>'會。 'testFunction =()=> {do stuff}'[see docs](https://www.typescriptlang.org/docs/handbook/functions.html) – JBC

回答

3

getter/setter方法可以申報簡單地在接口屬性:

interface A { 
    testGet: SomeType|null; 
} 

並指定getter函數內的type of this parameter

Object.defineProperty(A.prototype, "testGet", { 
    get (this: A) { 
     if(this.something) { 
      return this.something; 
     } 
     return null; 
    }, 
    enumerable: false, 
    configurable: true 
}); 
+0

好的,但我該如何引用'this'或對象有問題在defineProperty?它說它隱含的類型爲「任何」(我已經禁止在tsconfig中)。 – Sheph

+0

你可以指定'this'的類型作爲你的getter的參數。這將在編譯期間被刪除。 – Saravana