Home > Software engineering >  Unable to call forEach function from an Array in typescript
Unable to call forEach function from an Array in typescript

Time:12-15

I have a class with an array of object.

export interface Filter {
  sf?:Array<{key:string,value:string}>;
}

I try to use forEach function to loop and log each object value inside the array.

f : Filter = {sf:[{key:'a',value:'b'},{key:'c',value:'d'}]}; 

f.sf.forEach(element => {
  console.log(element.key);
});

However error appears inside the mongo db server.

[error] f.sf.forEach is not a function 0
node                           | TypeError: f.sf.forEach is not a function

how can I fix this error so the forEach works? thank you.

CodePudding user response:

As stated by your Filter interface, sf is optional.

You either need to make it non-optional like so:

export interface Filter {
  sf:Array<{key:string,value:string}>;
}

Another way of writing this is:

type SF = {
  key:string,
  value:string
}

interface Filter {
  sf: SF[];
}

Or use optional chaining like this:

f.sf?.forEach(element => {
  console.log(element.key);
});

CodePudding user response:

I think it's because sf is an optional price

  • Related