简体   繁体   English

由于TypeScript错误,无法在类型化数组上使用indexOf

[英]Unable to use indexOf on a Typed Array due to TypeScript error

I have defined an Interface , created an array of type Interface and am now attempting to use .indexOf , a method of an Array, and I am getting IDE error complaints that make no sense to me. 我已经定义了一个Interface ,创建了一个type Interface的数组,现在我正在尝试使用.indexOf ,一个Array的方法,我收到的IDE错误投诉对我来说毫无意义。 Hoping someone here may be able to lend a thought to solve this pickle. 希望有人在这里可以考虑解决这个问题。

Interface 接口

export interface IAddress {
  name: string,
  registrationId: number
}

Code

let friends: IAddress[];

// assume friends has a few elements...

let index = friends.indexOf((friend: IAddress) => {
  return !!(friend.name === 'some name');
});

TypeScript Errors: TypeScript错误:

Argument of type '(friend: IAddress) => boolean' is not assignable to parameter of type 'IAddress'.
Type '(friend: IAddress) => boolean' is missing the following properties from type 'IAddress': registrationId

If I were to remove the :IAddress from the typed def next to friend: I see this error instead. 如果我要从friend:旁边的类型def中删除:IAddress friend:我看到了这个错误。

Argument of type '(friend: any) => boolean' is not assignable to parameter of type 'IAddress'.
Type '(friend: any) => boolean' is missing the following properties from type 'IAddress': registrationId

Array.prototype.indexOf() receives a parameter searchElement and a second optional parameter fromIndex . Array.prototype.indexOf()接收参数searchElement和第二个可选参数fromIndex

Updated answer based on @Pixxl comment to use Array.prototype. 基于@Pixxl注释更新了答案以使用Array.prototype。 findIndex() to get index variable: findIndex()获取index变量:

const friends: IAddress[];

// assume friends has a few elements...
const index = friends.findIndex((friend: IAddress) => friend.name === 'some name');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM