7

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.

1
  • 1
    I guess your data object is not of type JSON? Use proper types or any. Commented Jun 9, 2016 at 11:47

2 Answers 2

17

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.*
}
Sign up to request clarification or add additional context in comments.

Comments

1

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];
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.