问题
Here is my JSON data which i get from the server
[
{
"property1": 1,
"property2": "asd",
"property3": 2
},
{
"property1": 1,
"property2": "asd",
"property3": 2
},
{
"property1": 1,
"property2": "asd",
"property3": 2
}
]
I want to define Immutable List object which uses this interface
export interface myObject {
propert1: number,
propert2: string,
propert3: number
}
I tried something like this but its not working :
private myObjectList: Immutable.List<myObject> = Immutable.List([]);
and then using angular $http
$http.get('my url to the json').then(function(data){
this.myObjectList = data.data;
});
But then myObjectList variable
is exactly the same as the json, instead I want to keep the Immutable List Object and somehow push the data in it with my specific Type.
In other words if the JSON objects are not exactly as the interface
myObject
, it should return an error
I also Tried this but then i get typescript error
$http.get('my url to the json').then(function(data){
this.myObjectList = Immutable.List(data.data);
});
error: Type 'List<{}>' is not assignable to type 'List<Queries>'
回答1:
Your first attempt doesn't assign an immutable list, it assigns the exact data to myObjectList
.
Your second attempt is correct, the error you are getting is because the compiler can't infer the response type.
Try:
$http.get('my url to the json').then(function(data){
this.myObjectList = Immutable.List(data.data as Queries);
});
来源:https://stackoverflow.com/questions/41238306/immutable-list-and-typescript-proper-way-to-define-an-array-of-objects-with-type