![](/img/trans.png)
[英]typescript TS1241: Unable to resolve signature of method decorator when called as an expression
[英]Error with decorator in Typescript: Unable to resolve signature of property decorator when called as an expression.ts(1240)
嘗試在 typescript 上創建一個簡單的裝飾器 function 時遇到問題。我不知道發生了什么。
這是裝飾器:
//Creating a decorator for loging the execution tyme of a method
export function logExecutionTime() {
return function (
target: any,
propertyKey: string,
descriptor: PropertyDescriptor
) {
return <any>descriptor;
};
}
當我像這樣在另一個文件上調用它時
@logExecutionTime();
我收到以下錯誤:
當作為表達式調用時無法解析屬性裝飾器的簽名.ts(1240)
如果我不強制裝飾器的返回類型為任何類型,我會得到上一個錯誤以及這個錯誤:
裝飾器 function 返回類型為“PropertyDescriptor”,但預計為“void”或“any”.ts(1271)
有人可以幫忙嗎? 我只是在學習裝飾器。 謝謝!
我試圖創建並調用一個簡單的裝飾器;
在調用裝飾器 function 的地方出現此錯誤:作為表達式調用時無法解析屬性裝飾器的簽名。
如果我不強制裝飾器的返回類型為任何類型,我會得到上一個錯誤以及這個錯誤:
裝飾器 function 返回類型為“PropertyDescriptor”,但預計為“void”或“any”.ts(1271)
內部 function 不應返回值。 在裝飾器中,您可以通過操作其描述數據來更改裝飾元素。 看看這個例子:
export function logExecutionTime() {
return function (
target: any,
propertyKey: string,
descriptor: PropertyDescriptor // this is the description we want to change
) {
const originalFunction = descriptor.value // store the declared fuction
descriptor.value = function(...args){ // set a new function
... // set up your timer
const result = originalFunction.apply(this, args) // run the declared function
... // process timer result
return result
}
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.