wzr1337
wzr1337

Reputation: 3767

How do you elegantly import AWS - Lambda in Typescript?

I am building a typescript project on aws lambda. As aws-sdk comes with type definitions already I would expect it also to hold a definition for aws lambda. But I seem to have to install @types/aws-lambda separately for it to work.

//import { Lambda } from "aws-sdk";
import { Context } from "aws-lambda";

module.exports.hello = async (event:any, context:Context) => {
  return {
    statusCode: 200,
    body: JSON.stringify({
      message: 'function executed successfully!',
      input: event,
    }),
  };
};

I would expect something like this being possible:

import { Lambda } from "aws-sdk";

module.exports.hello = async (event:any, context:Lambda.Context) => {
  return {
    statusCode: 200,
    body: JSON.stringify({
      message: 'function executed successfully!',
      input: event,
    }),
  };
};

but it is not ;)

So How do I do it correctly?

Upvotes: 5

Views: 1975

Answers (2)

dtruong0
dtruong0

Reputation: 81

You can explicitly only import the type definition

import type { Context } from "aws-lambda";

Upvotes: 0

hin522
hin522

Reputation: 59

The aws-sdk does not contain the types for lambda. So you will need both aws-sdk and @types/aws-lambda unfortunately. Also I would suggest to declare the @types/aws-lambda in the devDependencies of your package.json.

import * as AWS from "aws-sdk";
import { Context } from "aws-lambda";

module.exports.hello = async (event:any, context:Context) => {
  // eg. if you need a DynamoDB client
  // const docClient: AWS.DynamoDB.DocumentClient = new AWS.DynamoDB.DocumentClient({region: 'ap-southeast-2'});
  return {
    statusCode: 200,
    body: JSON.stringify({
      message: 'function executed successfully!',
      input: event,
    }),
  };
};

Upvotes: 5

Related Questions