'Why is TypeScript not returning APIGatewayProxyStructuredResultV2 for an api handler wrapped in another handler?
I'm trying to write a function which wraps aws lambda handlers and performs some logging. The lambdas are linked to API gateway so I've been using the APIGatewayProxyHandlerV2 type from the @types/aws-lambda package.
The function I have looks something like the below.
import { APIGatewayProxyHandlerV2 } from "aws-lambda";
const wrapApiHandler = (apiHandler: APIGatewayProxyHandlerV2) => {
const wrappedHandler: APIGatewayProxyHandlerV2 = async (
event,
context,
callback
) => {
try {
const result = await apiHandler(
event,
context,
callback
);
console.log(result);
return result;
} catch (err) {
console.error(err);
return {
statusCode: 500,
body: JSON.stringify({
error: "Failed to process request",
}),
};
}
};
return wrappedHandler;
};
When I try to do the above TypeScript complains about the wrappedHandler with the message below.
Type '(event: APIGatewayProxyEventV2, context: Context, callback: Callback<APIGatewayProxyResultV2<never>>) => Promise<...>' is not assignable to type 'APIGatewayProxyHandlerV2<never>'.
Type 'Promise<void | APIGatewayProxyResultV2<never>>' is not assignable to type 'void | Promise<APIGatewayProxyResultV2<never>>'.
Type 'Promise<void | APIGatewayProxyResultV2<never>>' is not assignable to type 'Promise<APIGatewayProxyResultV2<never>>'.
Type 'void | APIGatewayProxyResultV2<never>' is not assignable to type 'APIGatewayProxyResultV2<never>'.
Type 'void' is not assignable to type 'APIGatewayProxyResultV2<never>'.ts(2322)
What I need is for the TypeScript to recognise that a APIGatewayProxyStructuredResultV2 type is returned but I don't see why this isn't happening.
I can see the following...
type APIGatewayProxyHandlerV2<T = never> = Handler<APIGatewayProxyEventV2, APIGatewayProxyResultV2<T>>;
export type APIGatewayProxyResultV2<T = never> = APIGatewayProxyStructuredResultV2 | string | T;
Am I missing something?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
