不可变列表和Typescript定义类型为对象的数组的正确方法 [英] Immutable List and Typescript proper way to define an array of objects with type

查看:104
本文介绍了不可变列表和Typescript定义类型为对象的数组的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我从服务器获取的JSON数据

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
  }

]

我想定义使用此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([]);

,然后使用angular $http

$http.get('my url to the json').then(function(data){
   this.myObjectList = data.data;
});

但是myObjectList variable与json完全相同,相反,我想保留不可变列表对象,并以特定的类型将数据推入其中. 换句话说,如果JSON对象与interface myObject不完全相同,它将返回错误

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>'

推荐答案

您的第一次尝试未分配不可变列表,而是将确切的数据分配给了myObjectList.

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);
});

这篇关于不可变列表和Typescript定义类型为对象的数组的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆