Skip to content

Instantly share code, notes, and snippets.

@unfunco
Last active April 30, 2023 18:11
Show Gist options
  • Save unfunco/0c13c204c20a44e1967ef7fa00dd85b1 to your computer and use it in GitHub Desktop.
Save unfunco/0c13c204c20a44e1967ef7fa00dd85b1 to your computer and use it in GitHub Desktop.
Improved IntelliSense for Serverless and TypeScript

Improved IntelliSense for Serverless and TypeScript

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.

Before and after!

@unfunco
Copy link
Author

unfunco commented Apr 30, 2023

A simpler option:

import type { AWS } from '@serverless/typescript'

type ServerlessFunction = Exclude<AWS['functions'], undefined>[string]

export default <ServerlessFunction>{ /* ... */ }
  

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment