Typescript代码问题时,试图找到一个项目在实时数据库



我在Firebase云功能中的Typescript代码有一些问题。这个函数只是用来在数据库中搜索一条记录。要搜索的项通过req.query.val中作为参数给出的值提供。

我已经确认这一行返回了预期的内容:

const snpsv = snapshot.val();

问题在后面。

完整的代码如下:

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
import * as cors from "cors";
const corsHandler = cors();
admin.initializeApp();
exports.findVALUE = functions.https.onRequest(function(req, resp) {
resp.set("Access-Control-Allow-Origin", "*");
resp.set("Access-Control-Allow-Methods", "GET, POST");
let jsonResult;
corsHandler(req, resp, async () => {
if (req.query.val === undefined) {
jsonResult = {"Error": "A VALUE to search for must be provided to use this function."};
resp.send(jsonResult);
}
const refStr = "TopCollection/ContentCollection";
const dbRef = admin.database().ref(refStr);
dbRef.on("value", function(snapshot) {
const snpsv = snapshot.val(); // Getting a list of items.
// The forEach loop hereafter is not working !
// Wrong syntax or some other issue ?
snpsv.forEach((item) => {
if (item.get("val") == req.query.val) {
jsonResult = {"item": item.get("val2")};
resp.send(jsonResult);
}
});
});
}); // End corsHandler.
}); /* End of findVALUE */

下面是我得到的错误信息:

src/index.ts:43:22 - error TS7006: Parameter 'item' implicitly has an 'any' type.
43       snpsv.forEach((item) => {
~~~~
最后是数据库的总体结构:
TopCollection/ContentCollection
0  
fieldOne: ...
fieldTwo: ...
url: ...
otherField: ...
1  
fieldOne: ...
fieldTwo: ...
url: ...
otherField: ...
2  
fieldOne: ...
fieldTwo: ...
url: ...
otherField: ...
.....

当Typescript不知道item的类型时,就会发生这种情况。您可以检查是否使用--noImplicitAny编译器选项。如果你正在使用它,它可以防止TypeScript在未指定类型或不能从其用法中推断出类型时隐式地假设该类型为any。

要解决这个问题,您可以执行以下操作,

  1. 你可以像这样标记item的类型。snpsv.forEach((item: any) => {
  2. 你可以定义item对象的类型为接口

最新更新