2017-01-20 164 views
2

函數原型當我試圖定義一個函數的原型,我得到:定義與打字稿

錯誤TS2339:房產「applyParams」上不存在類型 「功能」。

Function.prototype.applyParams = (params: any) => { 
    this.apply(this, params); 
} 

如何解決這個問題?

+0

試試這個:http://stackoverflow.com/a/28020863/1142380 我不認爲你需要的「'prototype.'」部分 – ToastyMallows

+0

@ ToastyMallows,但然後我得到錯誤TS2339:屬性'applyParams'在類型'FunctionConstructor'上不存在。即使使用接口FunctionConstructor applyParams(params:any):any; } – Alexandre

回答

4

定義它的函數接口:

interface Function { 
    applyParams(params: any): void; 
} 

而你不希望使用箭頭功能,使this不會被綁定到外部環境。使用正則函數表達式:

Function.prototype.applyParams = function(params: any) { 
    this.apply(this, params); 
}; 

現在,這將工作:

const myFunction = function() { console.log(arguments); }; 
myFunction.applyParams([1, 2, 3]); 

function myOtherFunction() { 
    console.log(arguments); 
} 
myOtherFunction.applyParams([1, 2, 3]); 
+0

我也嘗試使用一個接口,它仍然得到錯誤。我嘗試過接口函數和接口FunctionConstructor – Alexandre

+0

@Alexandre你使用的是外部模塊嗎?在定義文件(* .d.ts *文件)中定義接口並在您的應用程序中引用 –

+1

@Alexandre您可以在[這裏]看到這個工作(https://www.typescriptlang.org/play/#src=interface %20Function%20%7B%0D 0A%%20%20%20個%20applyParams(PARAMS%3A%20any)%3A%20void%3B%0D 0A%%7D%0D 0A%%0D%0AFunction.prototype.applyParams% 20%3D%20function%20(PARAMS%3A%20any)%20%7B%0D 0A%%20%20%20個%20this(... PARAMS)%3B%0D 0A%%7D%3B%0D 0A% %0D%0Aconst%20func%20%3D%20function%20()%20%7B%20console.log(參數)%3B%20%7D%3B%0D%0Afunction%20myOtherFunc()%20%7B%0D% 0A%20%20%20%20console.log(參數)%3B%0D 0A%%7D%0D 0A%%0D%0Afunc.applyParams(%5B1%2C%202%2C%203%5D)%3B%0D %0AmyOtherFunc.applyParams(%5B1%2C%202%2C%203%5D)%3B) –