我有這個驗證中間件,我正在嘗試撰寫它以在發送請求時驗證空負載:
const _isMissing = (body: any): boolean => !body;
export const isMissing = Object.defineProperty(_isMissing, '_apiGatewayResponse', {
value: LAMBDA_400_RESPONSE,
});
interface ValidationFunction extends Function {
_apiGatewayResponse: APIGatewayProxyResult;
}
export function validateRequestBody(
handler: LambdaFunction,
validations: Array<ValidationFunction>,
): LambdaFunction {
const wrapper: LambdaFunction = async (
event: APIGatewayEvent,
): Promise<APIGatewayProxyResult> => {
const eventBody = event.body ? JSON.parse(event.body) : null;
for (const validation of validations) {
const invalidBody = validation(eventBody);
if (invalidBody) {
return validation._apiGatewayResponse || LAMBDA_400_RESPONSE;
}
}
const response = await handler(event);
return response;
};
return wrapper;
}
但是當我開始使用中間件功能時:
validateRequestBody(myPostFunction, [isMissing]);
我在isMissing說明時收到 TypeScript 錯誤
Property '_apiGatewayResponse' is missing in type '(body: any) => boolean' but required in type 'ValidationFunction'.
誰能幫我解決這個問題?我真的找不到任何類似的問題,希望得到任何幫助。
謝謝!
uj5u.com熱心網友回復:
isMissing( 來自_isMissing)的型別是(body: any) => boolean(一個函式接受一個型別的引數any并回傳一個boolean),但ValidationFunction需要一個_apiGatewayResponse屬性。即使您在運行時通過 添加屬性Object.defineProperty,也不會更改函式具有的編譯時型別。
您可以通過無害的型別斷言向 TypeScript 保證結果具有正確的型別,該斷言只斷言您可以輕松看到代碼添加的內容。例如:
type IsMissingFunction = ((body: any) => boolean) & ValidationFunction;
const _isMissing = (body: any): boolean => !body;
export const isMissing: IsMissingFunction = Object.defineProperty(
_isMissing as typeof _isMissing & Pick<ValidationFunction, "_apiGatewayResponse">,
'_apiGatewayResponse', {
value: LAMBDA_400_RESPONSE
}
);
游樂場鏈接
你可以只使用as IsMissingFunction而不是更冗長的as typeof _isMissing & Pick<ValidationFunction, "_apiGatewayResponse">:
type IsMissingFunction = ((body: any) => boolean) & ValidationFunction;
const _isMissing = (body: any): boolean => !body;
export const isMissing: IsMissingFunction = Object.defineProperty(
_isMissing as IsMissingFunction,
'_apiGatewayResponse', {
value: LAMBDA_400_RESPONSE
}
);
我更喜歡第一個版本的原因是,如果您稍后編輯IsMissingFunction(或ValidationFunction)以添加更多屬性,TypeScript 將在第一個示例中引發一個有用的錯誤,表明該函式不再符合IsMissingFunction. 隨著第二個例子中,你必須做一個真正的大改變它抱怨。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/383521.html
上一篇:條件泛型的回傳型別不正確
