Immutable List and Typescript proper way to define

2019-07-26 02:52发布

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条回答
该账号已被封号
2楼-- · 2019-07-26 03:39

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);
});
查看更多
登录 后发表回答