Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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,
                        });
                    });
                });
            }
}
like image 471
splunk Avatar asked Oct 04 '16 06:10

splunk


2 Answers

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;
        });
    });
like image 184
cartant Avatar answered Oct 20 '22 19:10

cartant


For Typescript version I came out with this solution:

db
  .ref(`jobs`)
  .orderByChild("counter")
  .on("value", (querySnapshot) => {
    const jobs: any[] = [];
    querySnapshot.forEach((jobRef) => {
      jobs.push(jobRef.val());
    });
    jobs.forEach(async (job) => {
      await minuteRT(job);
    });
    res.status(200).send("done!");
  });
like image 30
moshe beeri Avatar answered Oct 20 '22 20:10

moshe beeri