I am using TypeScript 5.7.3.
Installed @types/aws-lambda@8.10.147
.
TypeScript config:
{
"compilerOptions": {
"target": "ES2020",
"moduleResolution": "nodenext",
"module": "NodeNext",
"lib": ["ES2020"],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"skipDefaultLibCheck": true,
"rootDir": "./src",
"baseUrl": ".",
"outDir": "./dist",
"strictNullChecks": true,
"noImplicitAny": true
}
}
Now somewhere in my code:
import { APIGatewayRequestAuthorizerEventV2, APIGatewaySimpleAuthorizerWithContextResult } from 'aws-lambda'
type AuthReq = APIGatewayRequestAuthorizerEventV2
type AuthRes = Promise<APIGatewaySimpleAuthorizerWithContextResult<AdminAuthContext>>
export const authorize = async (event: AuthReq): AuthRes => {
const companyHeader = event?.headers['x-company']
const authHeader = event?.headers['authorization']
//....//
}
The event type extracted from @types/aws-lambda
(so that you don't need to go digging for it):
export interface APIGatewayRequestAuthorizerEventV2 {
version: string;
type: "REQUEST";
routeArn: string;
identitySource: string[];
routeKey: string;
rawPath: string;
rawQueryString: string;
cookies: string[];
headers?: APIGatewayRequestAuthorizerEventHeaders;
queryStringParameters?: APIGatewayRequestAuthorizerEventQueryStringParameters;
requestContext: APIGatewayEventRequestContextV2;
pathParameters?: APIGatewayRequestAuthorizerEventPathParameters;
stageVariables?: APIGatewayRequestAuthorizerEventStageVariables;
}
Now TS complains about the event?.headers
with the following: 'event.headers' is possibly 'undefined'.ts(18048)
.
Note that this is only TypeScript that complains. Esbuild for example works just fine and the code actually runs (well, there's nothing wrong with it so why wouldn't it).
So why is TS complaining about perfectly fine code? Any ideas? (I just think TS doesn't like me lately ;)
You're placing the ?.
after the wrong thing, it should go after the thing that could be undefined
(or null
). Here event
isn't undefined, it's AuthReq
, what can be undefined is the .headers
property on it, so you should place ?.
after that event.headers?.['x-company']
, not event
.