0

I'm having an error with my typescript application that I'm building. I'm using Ionic/Angular and one of the errors I'm getting is:

[20:12:30] typescript: C:/xampp/htdocs/project x/anonymous-social/src/pages/activity/activity.ts, line: 59 Argument of type '(data: DataSnapshot) => void' is not assignable to parameter of type '(a: DataSnapshot) => boolean'. Type 'void' is not assignable to type 'boolean'.

L58: (snapshot) => {

L59: snapshot.forEach(data => {

L60: data.ref.update({'read': "true"})

I'm not really sure why I'm getting this to be honest. Maybe someone can explain.. The code it is referencing is:

if(checkStatus) {
  this.database.database.ref('/users/'+this.userData.uid+'/replied_to')
  .orderByChild('read')
  .equalTo("false").once("value",
  (snapshot) => {
    snapshot.forEach(data => {
        data.ref.update({'read': "true"})
    });
  });
}

This is syntactically correct isn't it? What am I doing wrong? Any help would be great! Thank you

1
  • Hey Jane, can you also share the actual firebase data document? Commented Jun 8, 2018 at 0:35

1 Answer 1

2

You just need to return a boolean from your forEach callback function. In your case, since you don't want to cancel the iteration, return false. So something like:

snapshot.forEach(data => {
    data.ref.update({'read': "true"})
    return false // Add this
});

Much like the plain javascript forEach method, you can return a truthy value from the callback to stop the iteration. So the type for the callback function is actually:

(a: DataSnapshot) => boolean

You're giving a function that returns void instead, which is what typescript is complaining about. While your code should work perfectly fine at runtime (since undefined is falsy), it doesn't match the expected type so you get an typescript error.

From the firebase documentation on forEach:

function(non-null firebase.database.DataSnapshot)

A function that will be called for each child DataSnapshot. The callback can return true to cancel further enumeration.

Emphasis mine.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.