[英]typescript decorators with arrow functions
我必須在此實現中實現箭頭函數,並且我需要將來自 AWS 的輸入轉換為自定義 model 以避免對每個 API 執行相同的邏輯。 我想用裝飾器來做這個每個 function。 由於編譯器將其視為屬性,因此它不會找到描述符屬性並引發異常。 是否有解決方法來欺騙編譯器將箭頭 function 識別為實際的 function 並傳遞描述符?
@API(EndpointType.POST)
public login = async (event: Input): Promise<APIGatewayProxyResult> => {
... logic
}
export function API(apiType:EndpointType): any {
return (target: any, propertyKey: string, descriptor?: TypedPropertyDescriptor<any>) => {
descriptor.value = function(request) {
... logic
const bindedOriginalFunction = originalFunction.bind(this)
const result = bindedOriginalFunction(finalResult);
return result
}
return descriptor;
}
它必須是箭頭函數嗎?
class Foo {
async login(event: Input): Promise<APIGatewayProxyResult> { ... }
}
您的情況下的箭頭函數不是方法(對象擁有的函數)。 您有一個屬性,其中包含其他人擁有的函數(箭頭函數)。
裝飾器實際上只是一個 function 接受功能並返回 function:
function API(endpoint) {
return (target) => {
/*do stuff*/
}
}
所以你可以這樣做
const undecorated = (someParams) => ...;
const decorated = API(EdpointType.POST)(undecorated);
它可以更流暢地
const func = API(EndpointType.Post)((someParams) => ...);
您甚至可以在 class 內部執行此操作
class Foo {
bar = API(EndpointType.POST)((someParams) => {
const someOtherPropertyAccess = this.property;
/* body of the function */
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.