The aws-nodejs-typescript
template provided by the Serverless Framework
scaffolds Lambda functions in such a way that it's difficult for an IDE to
infer types correctly. For example, the following code defines a Lambda function
as a plain object literal, this is what is generated when creating a new service.
import { handlerPath } from '@libs/handler-resolver'
export default {
handler: `${handlerPath(__dirname)}/handler.main`,
events: [/* … */],
}
When editing this file, IntelliSense is not available because the IDE does not
have enough information. As a workaround we can create a new
ServerlessFunction
type derived from a nested key in the provided AWS
type.
Create a new file src/libs/types.ts
and add the following code:
import type { AWS } from '@serverless/typescript'
type DeepKey<Obj extends object, K0 extends string> = K0 extends keyof Obj
? Obj[K0]
: { [K1 in keyof Obj]: DeepKey<Extract<Obj[K1], object>, K0> }[keyof Obj]
export type ServerlessFunction = DeepKey<AWS, 'functions'>[0]
Update src/functions/<function>/index.ts
to include the hint:
import { handlerPath } from '@libs/handler-resolver'
+import type { ServerlessFunction } from '@libs/types'
-export default {
+export default <ServerlessFunction>{
handler: `${handlerPath(__dirname)}/handler.main`,
events: [/* … */],
}
Your IDE should now be able to infer the correct fields.
A simpler option: