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

时间:2019-01-02 02:24:57

标签: javascript typescript typescript-typings

我已经定义了一个Interface,创建了一个type Interface数组,现在正尝试使用.indexOf,这是一个数组方法,并且我收到了IDE错误投诉,但没有对我而言希望这里的某人能够提出解决该酱菜的想法。

界面

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

代码

let friends: IAddress[];

// assume friends has a few elements...

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

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

如果我要从:IAddress旁边的键入def中删除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

1 个答案:

答案 0 :(得分:3)

Array.prototype.indexOf()接收参数searchElement和第二个可选参数fromIndex

基于@Pixxl注释的更新答案,以使用Array.prototype. findIndex()获得index变量:

const friends: IAddress[];

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