Reputation: 28128
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?
Upvotes: 0
Views: 3823
Reputation: 4637
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);
}
Upvotes: 1