0

I am reading JSON data in my typescript app. I found this tool JSON2TS that creates interfaces from JSON, so that typescript knows what the json must contain.

My json:

{
"questions": [
    {
    "text": "Is this a question?",
    "answers": ["yes", "no", "maybe", "maybe not"],
    "correct":1
    }]
}

The generated interfaces:

declare module namespace {

export interface Question {
    text: string;
    answers: string[];
    correct: number;
}

export interface RootObject {
    questions: Question[];
}

}

These interfaces need to be saved in a d.ts file and referenced in the code. My question: how do I actually use the json data after loading it with ajax?

4
  • I'm not sure about what you ask for. If you have an object that you get from some ajax-service, you have access to all its properties and methods as usual. All these interfaces are doing is to give you the ability to type it properly. Commented Jun 13, 2016 at 16:23
  • Yes, but typescript won't allow that if you don't declare the type. Of course, you can always use "any" as the type, but then you don't have the IDE advantages (code completion and error checking) Commented Jun 13, 2016 at 20:12
  • Aha, so your question was how to type your json-object, not how to use the json data. Commented Jun 13, 2016 at 20:15
  • Choosing the right wording when you don't know what the exact problem is can sometimes be tricky... Commented Jun 13, 2016 at 20:16

1 Answer 1

1

With that definition file, if your code is in the namespace namespace, you could do it like this:

var questions = <RootObject>functionThatReturnsYourJSONData().questions;

If your code is not in the namespace namespace, this should work.

var questions = <namespace.RootObject>functionThatReturnsYourJSONData().questions;

In either case, this would be strongly typed:

if (questions.length > 0) {
    console.log(questions[0].text);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it works! Also, is the "RootObject" really necessary ?
If the function that returns your data is already typed as a RootObject, then no. I think RootObject is an artifact of the JSON typer you were using.

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.