Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
129
rated 0 times [  136] [ 7]  / answers: 1 / hits: 62020  / 12 Years ago, sat, november 10, 2012, 12:00:00

I have the following C# class:



public class JsonBackup
{
public int Added { set; get; }
public int DEVCount { set; get; }
public int DS1Count { set; get; }
public IList<ViewEvent> Events { get; set; }
public IEnumerable<string> Errors { set; get; }
public int Rejected { set; get; }
public bool Success { set; get; }
public int Updated { set; get; }
}


and this code to return JSON data to my browser:



return Json(new JsonBackup
{
Added = added,
DEVCount = devCount,
DS1Count = ds1Count,
Events = t.Events,
Rejected = rejected,
Success = true,
Updated = updated
});


The data is returned here:



 $.ajax(/Backup/Data/Backup,
{
cache: false,
dataType: 'json',
type: 'POST'
})
.done(function (data: ) {
console.log(data);
backupDone(data, ajaxElapsed);
});


and used in other places and also here:



   $.each(data.Events, function (i, item) {
$(#stats-list li:eq(+(4+i)+)).after('<li>' + item.Description + ' : ' + item.Elapsed + ' ms</li>');
});


Is it possible for me to create a TypeScript type and assign data to that type so I could
for example get intellisense when selecting such things as



data.Added or data.DEVCount etc?

More From » typescript

 Answers
229

Simplest way to achieve that is to create interface for IJsonBackup and when you receive json just cast it to IJsonBackup



interface IViewEvent
{
}

interface IJsonBackup
{
Added : number;
DEVCount : number;
DS1Count : number;
Events : IViewEvent[];
Errors : string[];
Rejected : number;
Success : bool;
Updated : number;
}


In your class definition:



backupDone(data: IJsonBackup, ajaxElapsed: any)
{
}

$.ajax(/Backup/Data/Backup,
{
cache: false,
dataType: 'json',
type: 'POST'
})
.done(function (data: any) {
console.log(data);
backupDone(<IJsonBackup>data, ajaxElapsed);
});

[#82070] Thursday, November 8, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shylaelisan

Total Points: 37
Total Questions: 94
Total Answers: 110

Location: Angola
Member since Tue, May 5, 2020
4 Years ago
;