【问题标题】:error TS2339: Property 'filter' does not exist on type for custom interface错误 TS2339:自定义接口的类型上不存在属性“过滤器”
【发布时间】:2018-10-17 08:31:45
【问题描述】:

我为对象数组创建了一个接口

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

【问题讨论】:

  • 就用type UpdateMediaList = ContactResponse[]?
  • @jcalz “只需使用类型 UpdateMediaList = ContactResponse[]?”在哪里?
  • 而不是您当前对UpdateMediaList 的定义,这只是说“这个东西具有带有ContactResponse 值的数字键属性”而不是“这是一个ContactResponse 值的数组”。一个实际的数组具有所有这些数组方法,例如filter()。数字索引的对象可能不会。
  • 即所有数组都具有数字索引属性,但并非所有具有数字索引属性的对象都是数组。
  • 您检查过响应的类型吗?我怀疑它是数组类型

标签: angular typescript


【解决方案1】:

你的定义:

export interface UpdateMediaList {
    [index: number]: ContactResponse;
}

没有定义 TypeScript Array,而只是一个带有数字键的对象,其值为 ConstactResponse 对象。 Array&lt;T&gt; 确实有 numeric-keyed properties,但它也有所有 Array 方法,如 filter(),你显然依赖这些方法。

以下内容符合您的 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

这有意义吗?祝你好运。

【讨论】:

  • 非常感谢。这现在确实有意义。
猜你喜欢
  • 2019-03-02
  • 2021-06-30
  • 2016-11-17
  • 2019-01-21
  • 2016-08-13
  • 2017-12-20
  • 2016-11-14
  • 2017-10-24
  • 2021-08-10
相关资源
最近更新 更多