且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

'(snap: DataSnapshot) => 类型的参数void' 不能分配给 '(a: DataSnapshot) => 类型的参数.布尔值

更新时间:2022-11-30 12:57:29

DataSnapshot 中的forEach 方法有这样的签名:

forEach(action: (a: firebase.database.DataSnapshot) => boolean): boolean;

因为 action 可以返回 true 以使枚举短路并提前返回.如果返回虚假值,则枚举正常继续.(文档中提到了这一点.)p>

为了安抚 TypeScript 编译器,最简单的解决方案是返回 false(继续枚举子快照):

数据库().ref("用户").orderByChild("id").on("值", (快照) => {让项目 = [];snapshot.forEach((snap) => {项目.推({uid: snap.val().uid,用户名:snap.val().username});返回假;});});

I've already read several questions and answers about this problem but wasn't able to solve it.

I'm using Ionic2 and I have a method which retrieves data from Firebase Database v3. I don't understand why I get following error in console when I do ionic serve:

Error TS2345: Argument of type '(snap: DataSnapshot) => void' is not assignable to parameter of type '(a: DataSnapshot) => boolean'.
  Type 'void' is not assignable to type 'boolean'.

This is the method:

constructor(private http: Http) {

    firebase.database().ref('users').orderByChild("id").on("value", function(snapshot){
                    let items = [];
                    snapshot.forEach(snap => {
                        items.push({
                            uid: snap.val().uid,
                            username: snap.val().username,
                        });
                    });
                });
            }
}

The forEach method in the DataSnapshot has this signature:

forEach(action: (a: firebase.database.DataSnapshot) => boolean): boolean;

as the action can return true to short-circuit the enumeration and return early. If a falsy value is returned, enumeration continues normally. (This is mentioned in the documentation.)

To appease the TypeScript compiler, the simplest solution would be to return false (to continue enumerating the child snapshots):

database()
    .ref("users")
    .orderByChild("id")
    .on("value", (snapshot) => {
        let items = [];
        snapshot.forEach((snap) => {
            items.push({
                uid: snap.val().uid,
                username: snap.val().username
            });
            return false;
        });
    });