简体   繁体   English

使用 Firebase 可调用函数使用 TypeScript 进行类型检查

[英]Type Checking with TypeScript using Firebase Callable functions

I am using TypeScript to write callable Cloud Functions with Firebase, and it is important that I receive data of a certain type.我正在使用 TypeScript 使用 Firebase 编写可调用的云函数,并且接收某种类型的数据很重要。

My function declaration is as follows:我的函数声明如下:

export const questionnaireSubmit = https.onCall(async (data: questionnaireDoc): Promise<apiOut> => {})

Because I defined questionnaireDoc as an interface, using data instanceof questionnaireDoc gives the following error in my IDE:因为我将questionnaireDoc定义为一个接口,所以在我的 IDE 中使用data instanceof questionnaireDoc会出现以下错误:

'questionnaireDoc' only refers to a type, but is being used as a value here.ts(2693)

When calling this function in a TypeScript program, I can use the HttpsCallable<parameterType,returnType> type from "firebase/functions" to define its input type, but this relies on the client code explicitly setting the type and using a language that supports explicit types.在 TypeScript 程序中调用此函数时,我可以使用“firebase/functions”中的HttpsCallable<parameterType,returnType>类型来定义其输入类型,但这依赖于客户端代码显式设置类型并使用支持显式类型。

Right now, I am checking the existence of necessary properties using the following within my cloud function:现在,我正在我的云函数中使用以下内容检查必要属性的存在:

        switch (undefined) {
            case <unknown>data.property1:
            case <unknown>data.property2:
            case <unknown>data.property3:
            case <unknown>data.property4:
            case <unknown>data.property5:
            case <unknown>data.property6:
            case <unknown>data.property7:
            case <unknown>data.property8:
            case <unknown>data.property9:
                throw new https.HttpsError("invalid-argument", "Missing required field(s)");
        }

But this workaround does not seem necessary or scalable.但这种解决方法似乎没有必要或可扩展。

What is the best practice to ensure inputs passed to Firebase Callable functions are correct within the function using TypeScript?使用 TypeScript 确保传递给 Firebase 可调用函数的输入在函数中正确的最佳做法是什么?

Thanks!谢谢!

The onCall function is generic and can take both a request and a return type. onCall函数是通用的,可以接受请求和返回类型。 I think this might help:我认为这可能会有所帮助:

export const questionnaireSubmit = 
  https.onCall<questionnaireDoc,apiOut>(async (data) => {
    // ...
  })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM