Typescript 对于可以包含具有不同属性的对象的数组,该接口是什么样子的?
我创建了以下接口和服务。请注意,“视图”属性将包含一个对象数组,但根据其使用位置,这些对象将具有不同的属性:Typescript 对于可以包含具有不同属性的对象的数组,该接口是什么样子的?,typescript,Typescript,我创建了以下接口和服务。请注意,“视图”属性将包含一个对象数组,但根据其使用位置,这些对象将具有不同的属性: 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
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; }'
如何使我的界面更通用,以便在以后使用查看某些属性的代码时,不会出现上述语法错误?只要
任何[]
都可以:
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
您的类型定义
{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');
}
并尽可能将用法转换为正确的类型:
(<City[]>this.view)[this.home.rowSelected].tests.length > 0
(this.view)[this.home.rowSelected].tests.length>0
(<City[]>this.view)[this.home.rowSelected].tests.length > 0