Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you elegantly import AWS - Lambda in Typescript?

Tags:

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?

like image 710
wzr1337 Avatar asked Sep 12 '18 07:09

wzr1337


1 Answers

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,
    }),
  };
};
like image 71
hin522 Avatar answered Oct 07 '22 15:10

hin522