gpt4 book ai didi

angular - 错误 TS2339 : Property 'filter' does not exist on type for custom interface

转载 作者:行者123 更新时间:2023-12-02 00:34:33 24 4
gpt4 key购买 nike

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

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

最佳答案

你的定义:

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

没有定义 TypeScript Array , 但只是一个带有数字键的对象,其值为 ConstactResponse对象。一个Array<T>确实有 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包含您需要的所有方法。

这有意义吗?祝你好运。

关于angular - 错误 TS2339 : Property 'filter' does not exist on type for custom interface,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50215823/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com