从不同事件触发的 lambda 的打字稿语法

问题描述

使用无服务器框架,我定义了一个可以每小时触发一次或通过 SNS 触发的 lambda

  ...
  functions: {
    fooAction: {
      handler: 'handler.fooAction',events: [
        {
          schedule: 'rate(1 hour)',},{
          sns: {
            topicName: 'fooTopic',],...
  }
  ...

定义 fooAction 函数时正确的打字稿语法是什么?

我试过了

import { SNSHandler,ScheduledHandler} from 'aws-lambda';
...
export const fooAction: ScheduledHandler | SNSHandler = async (evt) => { ... };

evt 解析为 any

解决方法

aws-lambda sdk 中似乎有一个类型 Handler,它是通用的,可以用于这样的情况,

import { SNSEvent,EventBridgeEvent,Handler } from 'aws-lambda';

const fooHandler: Handler<SNSEvent | EventBridgeEvent<any,any>> = (event) => {
    if ('Records' in event ) {
        // SNSEvent
        const records = event.Records;
        // so something
    } else {
        const { id,version,region,source } = event;
    }
};

您也可以根据这两种不同的函数类型定义自己的类型。

type CustomEvent = (event: SNSEvent | EventBridgeEvent<"Scheduled Event",any>,context: Context,callback: Callback<void>) => Promise<void> | void

然后,在你的 lambda 函数中使用这个新类型,

const fooHandler: CustomEvent = (event) => {
    if ('Records' in event ) {
        // SNSEvent
        const records = event.Records;
        // so something
    } else {
        const { id,source } = event;
    }
};