Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript Error - Type '{}' is not an array type or a string type

I have the following code:

forkJoin([
    this.restangular.all(this.commonService.getHospitalURI()).getList(),
    this.restangular.all(this.commonService.getAgeGroupURI()).getList()
    ]).subscribe(responses => {

    const hospital_result = responses[0];
    // Error because of the line below
    const agegroup_result = Array.from(responses[1]);

    console.log('hospital ' + JSON.stringify(hospital_result))
    console.log('agegroup ' + JSON.stringify(agegroup_result))

    for (const productID_hospital of hospital_result[0]['product']) {

        for (const productID_agegroup of agegroup_result) {
          // Do Something here
        }
    }
  })

I'm using Angular 5, doing a forkjoin to call a response sequentially. This part is completely fine. But the error comes when it is trying to parse the JSON.

I get this error:

src/app/layout/insurance-list/insurance-list.component.ts(75,48): error TS2345: Argument of type '{}' is not assignable to parameter of type 'Iterable<{}>'.
Property '[Symbol.iterator]' is missing in type '{}'.

If I change

const agegroup_result = Array.from(responses[1]);

to

const agegroup_result = responses[1];

Then I'll get an error:

src/app/layout/insurance-list/insurance-list.component.ts(85,50): error TS2495: Type '{}' is not an array type or a string type.

I don't understand why I am having this error. I am parsing the JSON correctly as it returns an array first. I am unable to run my project due to this error.

Edit:

Here is the link to the JSON for agegroup_result: https://plnkr.co/edit/hzkPXqWfGmNNgHuHwAzT?p=catalogue

It's named as agegroup.json

Edit 2:

console.log(responses[1] instanceof Array)

The above code returns true. Response[1] is an Array.

like image 811
Nathanael Avatar asked Mar 06 '23 21:03

Nathanael


2 Answers

I tried to map my "any" type of data to a specific DataModel type, and I got the same error message. so, to fix the problem I suggest you use index of array instead, here we go:

Change this line of code:

const agegroup_result = Array.from(responses[1]);

To:

const ages = responses[1];

Then when you do "for" loop, please use index of array:

for ( const i of Object.keys(ages)){
    console.log(ages[i].propertyName);
}

I hope this can help to fix your problem.

like image 66
Dimang Chou Avatar answered Mar 14 '23 21:03

Dimang Chou


its an object, not an array. try and get all the keys from the object using the Object.Keys functions.

const agegroup_result = Object.keys(responses);

then you can iterate over the keys of the responses object, or you can map the response to an array type.

if you add a console log of the responses object and the desired object/array expected then we might be able to help a bit more.

like image 29
Daniel Netzer Avatar answered Mar 14 '23 20:03

Daniel Netzer