2
我返回從服務器使用AJAX jQuery的一個例子地圖JSON對象爲打字稿對象
[{"Name":"Name1","ResultSet":[{"Id": 1,"Name":"Name1"}, {"Id": 2,"Name":"Name2"}]},{"Name": "Name11", "ResultSet": [{"Id": 11, "Name": "Name11"}, {"Id": 22, "Name": "Name22"}]}]
而且對象的數組,我有以下的打字稿對象我要地圖
interface IResult {
name: string;
resultSet: any;
}
export class Result implements IResult {
constructor(public name: string, public resultSet: any) { }
}
我正在處理結果的方式,
dataService.execute(function (results) {
$(results).each(function (index, element) {
console.log(element.Name);
$.each(element.ResultSet, function (key, value) {
$.each(value, function (key, value) {
console.log(key + ' - ' + value);
});
});
});
});
在VS 2013中,編譯器抱怨:
The property 'Name' does not exist on value of type 'Element'.
有沒有辦法將返回的對象集合映射到TS結果對象數組?
感謝
UPDATE 我結束了循環如下:
var result = <Array<IResult>>results;
$.each(result, function (index, item) {
// item is Result instance
// item.name
console.log(item.name);
// item.resulSet
$.each(item.resultSet, function (key, val) {
// val is single Object (one result)
$.each(val, function (k, v) {
// k,v => key/value for each property on result
console.log(k + ' - ' + v);
});
});
});