Abdeali Chandanwala
Abdeali Chandanwala

Reputation: 8828

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.

Upvotes: 7

Views: 17299

Answers (2)

Wojciech Kwiatek
Wojciech Kwiatek

Reputation: 6802

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.*
}

Upvotes: 17

Batman
Batman

Reputation: 15

You can check if that name field exists in JSON data by

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) <-- check if data.name is present
        {
            details = this.funds[j];
        }
    }

Upvotes: 1

Related Questions