網站搜尋

javascript - Typescript 裝飾類別新增方法


我想要在一個裝飾過的類別中新增一個方法。一切運作良好,但編譯器抱怨該方法不存在,我該如何讓編譯器滿意?

export function decorate( constructor : Function ) {

  constructor.prototype.someMethod = function () {

  }

} 

@decorate
class Test {
  constructor() {
    //Property 'someMethod' does not exist on type 'Test'.
    this.someMethod();
  }
}

答案#1

你可以使用:

(<any>this).someMethod();

或:

this['someMethod']();

你不能使用介面來檢查 this 是否包含方法 someMethod(),因為你實際上並沒有實作這個介面,所以我認為這兩個是唯一的選擇...