Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property 'name' does not exist on type 'JSON' in typescript / angularJs 2

I am using typescript language in angularjs 2 to my REST api application, the problem is - typescript gives compile time error of

[ts] Property 'name' does not exist on type 'JSON'.any

WHEN I TRY TO ACCESS INCOMING JSON Object, my function code is below

createPerformanceChart(data: JSON) {
    // Show Up the Fund Details Data 
    var details: any;
    for(var j = 0 ; j < Object.keys(this.funds).length; j++)
    {
        if(data.name == this.funds[j].name) // data.name throws Error
        {
            details = this.funds[j];
        }
    }
}

How can I convert the JSON or access JSON Object - such that it does not throw compile time error and let me compile the code.

like image 896
Abdeali Chandanwala Avatar asked Jul 15 '26 08:07

Abdeali Chandanwala


1 Answers

If you want to make strong types

You have to change type of response (JSON) to something more specific using e.g. interface:

interface IPerformanceData {
  name: string;
}

And then use this as a type for incoming response:

createPerformanceChart(data: IPerformanceData) {
  // you can now use: data.name
}

If you don't care

Just make it a type of any:

createPerformanceChart(data: any) {
  // you can now use any property: data.*
}
like image 149
Wojciech Kwiatek Avatar answered Jul 19 '26 04:07

Wojciech Kwiatek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!