对于可以包含具有不同属性的对象的数组,接口是什么样的?

时间:2014-08-31 09:21:06

标签: typescript

我创建了以下界面和服务。请注意,view属性将包含一个对象数组,但根据它的使用位置,这些对象将具有不同的属性:

interface IAdminGridService  {
    view:   {any} []; // An array of objects. It could be an array of contents, 
                      // cities, streets etc. If it was an array of city objects
                      // then these objects might in themselves contain a list 
                      // of street objects. I don't need any checks here. Just 
                      // want it to be an array of any kind of object.
}

class AdminGridService implements IAdminGridService {
    view = getViewData('city'); // Returns an array of objects
}

在代码的另一部分我想这样做:

this.grid.view[this.home.rowSelected].tests.length > 0

代码正确地找到this.grid.view但是给出了一条消息:

The property 'tests' does not exist on value of type '{ any: any; }'

如何让我的界面更具通用性,以便当我以后拥有查看某些属性的代码时,我不会像上面那样得到语法错误?

2 个答案:

答案 0 :(得分:1)

只需any[]即可:

interface IAdminGridService  {
    view:   any[]; // An array of objects. It could be an array of contents, 
                   // cities, streets etc. If it was an array of city objects
                   // then these objects might in themselves contain a list 
                   // of street objects. I don't need any checks here. Just 
                   // want it to be an array of any kind of object.
}


var grid:IAdminGridService;
grid.view[this.home.rowSelected].tests.length > 0

答案 1 :(得分:1)

您的类型定义{any}[]并不代表您认为的含义。它表示" 具有名为any的属性的对象数组,其类型为any "。换句话说,它与{any:any}[]相同。


如果一个类中存储对象的类型相同,则可以添加如下类型参数:

interface IAdminGridService<T> {
  view: T[];
}

class AdminGridService implements IAdminGridService<City> {
  // this class will treat this.view as a City[]
  // where City is the type definition of the object you are putting into the array
  this.view = getViewData('city');
}

否则,您可以使用无类型方法:

interface IAdminGridService  {
  view: any[];
}

并尽可能将使用类型转换为正确类型:

(<City[]>this.view)[this.home.rowSelected].tests.length > 0