Let's modify this from @types/aws-lambda to clearly indicate that our intention is for pathParameters
to not be null and have a specific format.
export interface APIGatewayProxyEventBase<TAuthorizerContext> {
body: string | null;
headers: APIGatewayProxyEventHeaders;
multiValueHeaders: APIGatewayProxyEventMultiValueHeaders;
httpMethod: string;
isBase64Encoded: boolean;
path: string;
pathParameters: APIGatewayProxyEventPathParameters | null;
// ...snip...
}
export interface APIGatewayProxyEventPathParameters {
[name: string]: string | undefined;
}
In our codebase, we can specify that fooId is not null
declare module "aws-lambda/trigger/api-gateway-proxy" {
export interface APIGatewayProxyEventPathParameters {
fooId: string;
}
}
export const handler: APIGatewayProxyHandler = async (event) => {
// This check is still necessary
if (!event.pathParameters) {
throw new Error("parameter is empty");
}
// Without declaration merging, fooId could be string or undefined,
// but now it's just a string
const { fooId } = event.pathParameters;
To get rid of the need for if (!event.pathParameters)
, I tried this:
declare module "aws-lambda/trigger/api-gateway-proxy" {
export interface APIGatewayProxyEventBase<T> {
pathParameters: APIGatewayProxyEventPathParameters;
}
export interface APIGatewayProxyEventPathParameters {
fooId: string
}
}
We encountered the following error as a result:
error TS2428: All declarations of 'APIGatewayProxyEventBase' must have identical type parameters.
error TS2717: Subsequent property declarations must have the same type. Property 'pathParameters' must be of type 'APIGatewayProxyEventPathParameters | null', but here has type 'APIGatewayProxyEventPathParameters'.
Is it possible for event
to be of type
{ pathParameters: { fooId: string }, ... }
instead of { pathParameters?: { fooId: string }, ... }
?