Immutable List and Typescript proper way to define an array of objects with type

痞子三分冷 提交于 2019-12-11 05:11:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!