0

I have a piece of code where I have data variable with given declaration. But when I loop through data object I am getting error as below:

"cannot invoke an expression whose type lacks a call signature"


export class AppComponent {
  title = 'app works!';
  data : any[] | Observable<any[]>;

  constructor()
  {
    this.data.forEach(function(d)
    {

    });
  }
}

Not sure it is typescript issue or due to incorrect type declaration.

manish
  • 61
  • 8
  • The `forEach` method means something very different for an array and an observable (re observable, see [this answer](https://stackoverflow.com/a/35399823) found in a [web search](https://duckduckgo.com/?q=rxjs+observable+foreach)), so it doesn't make much sense to call `forEach` on a variable that might contain either an array or an observable. Where are you getting `this.data` from that motivated you to give it that union type? – Matt McCutchen Sep 27 '18 at 01:39
  • actually it comes from a node module package of ngx-formly/core and we are looping through templateoption of that . But i got solution of that. by doing type cast. like var result = data as any[]; – manish Sep 28 '18 at 06:25

1 Answers1

0

I got the solution by doing type cast as below

var result = this.data as any[];
result.forEach(function(d)
{

});
manish
  • 61
  • 8