我为对象数组创建了一个接口
export interface UpdateMediaList {
[index: number]: ContactResponse;
}
interface ContactResponse {
contactId: number;
email: string;
firstName: string;
imgDisplayPath: string;
inMediaList: true;
jobTitle: string;
lastName: string;
mediaOutletId: number;
mediaOutletName: string;
openRate: string;
phone: string;
responseRate: string;
secureRate: string;
}
然后我在我的服务中使用它......
postUpdateMediaList(param, body, url = this.urls.mediaList.updateMediaList) {
let params = new HttpParams();
params = params.set('sortType', param.sortType);
params = params.set('numRows', param.numRows);
params = params.set('startRow', param.startRow);
return this.http.post<UpdateMediaList>(url, body, {params: params});
}
现在我收到此错误
ERROR in src/app/modules/media-list/containers/media-list-builder/media-list-builder.component.ts(142,22): error TS2339: Property 'filter' does not exist on type 'UpdateMediaList'
这段代码中包含哪些内容:
this.mediaList = response
.filter(items => items.inMediaList === true)
.map(items => items.contactId);
while (this._contacts.value.length !== 0) {
this._contacts.removeAt(0);
}
答案 0 :(得分:3)
您的定义:
export interface UpdateMediaList {
[index: number]: ContactResponse;
}
不定义TypeScript Array
,而只定义具有数值键的对象,其值为ConstactResponse
个对象。 Array<T>
确实有numeric-keyed properties,但它也包含filter()
之类的所有Array
方法,您显然依赖这些方法。
以下内容符合您的UpdateMediaList
定义:
declare const someContactResponse: ContactResponse;
const weirdUpdateMediaList: UpdateMediaList = {0: someContactResponse};
如您所见,weirdUpdateMediaList
具有数字键属性,但不是数组。您不希望允许此代码:
weirdUpdateMediaList.filter(x => true); // error at compile time
因为它会在运行时以weirdUpdateMediaList.filter is not a function
爆炸。
假设您实际上从后端获得了Array
,那么您应该使用Array
这样的代替UpdateMediaList
的定义:
export type UpdateMediaList = Array<ContactResponse>;
或等同于
export type UpdateMediaList = ContactResponse[];
然后,如果你试过这个,你会收到一个错误:
const weirdUpdateMediaList: UpdateMediaList = {0: someContactResponse};
// error! not assignable to type 'ContactResponse[]'.
// Property 'length' is missing in type '{ 0: ContactResponse; }'.
可以安全地假设UpdateMediaList
类型的任何对象都是具有您需要的所有方法的实际Array
。
这有意义吗?祝你好运。