代码之家  ›  专栏  ›  技术社区  ›  pmiranda

带TypeScript的Middy,回调类型

  •  0
  • pmiranda  · 技术社区  · 4 年前

    我正在尝试使用TyepScript witn Middy 在Lambda API调用上。 我的部分代码:

    // 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);
    

    我试着用:

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

    但我发现了这个错误 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'.
    

    我应该用什么类型的 callback myFunction的参数?

    0 回复  |  直到 4 年前
        1
  •  0
  •   tmhao2005    4 年前

    问题是第二个论点应该是 Context 键入其签名而不是回调。

    context callback 分别作为第二、第三个参数,如下所示:

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