Search code examples
typescriptmiddy

Middy with TypeScript, callback type


I'm trying to use TyepScript witn Middy on a Lambda API call. Part of my code:

// My types definition
import BodyRequestType from 'types';

// some code

async function myFunction (
  event: { body: BodyRequestType },
  callback: ??? <--
): Promise<void> {
  // my code
  return callback(null, {
    statusCode: 200,
    body: JSON.stringify(data)
  });
}

export const handler = middy(myFunction);

I tried to use:

import { Callback } from 'aws-lambda'
// then...
callback: Callback

But I get this error on middy(myFunction):

TS2345: Argument of type '(event: { body: BodyRequestType; }, callback: Callback<any>) => Promise<void>' is not assignable to 
parameter of type 'AsyncHandler<Context>'.
Type '(event: { body: BodyRequestType; }, callback: Callback<any>) => Promise<void>'
is not assignable to type '(event: any, context: Context, callback: Callback<any>) => void'.
Types of parameters 'callback'and 'context' are incompatible.
Type 'Context' is not assignable to type 'Callback<any>'.
Type 'Context' provides no match for the signature '(error?: string | Error | null | undefined, result?: any): void'.

What type should I use on callback argument of myFunction?


Solution

  • The problem is the 2nd argument is supposed to be Context type in its signature instead of the callback.

    Since context is required so you just set context and callback as 2nd, 3rd argument respectively as following:

    
    import { Context, Callback } from 'aws-lambda';
    
    
    async function myFunction (
      event: { body: BodyRequestType },
      context: Context,
      callback: Callback 
    ) {
      // ...
    }