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

Pix*_*xxl 4 javascript typescript typescript-typings

我已经定义了一个Interface,创建了一个数组type Interface,现在正在尝试使用.indexOf,一个数组的方法,但我收到了 IDE 错误投诉,这对我来说毫无意义。希望这里有人能够提出解决这个问题的想法。

界面

export interface IAddress {
  name: string,
  registrationId: number
}
Run Code Online (Sandbox Code Playgroud)

代码

let friends: IAddress[];

// assume friends has a few elements...

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

打字稿错误:

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
Run Code Online (Sandbox Code Playgroud)

: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
Run Code Online (Sandbox Code Playgroud)

Yos*_*ero 9

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');
Run Code Online (Sandbox Code Playgroud)

  • 太棒了,我没有意识到“index”和“indexOf”适用于原始值,而“find”和“findIndex”适用于更多类似对象的值。我还想建议将此答案更改为使用“findIndex”的答案,因为它可以完成相同的任务,而无需在范围之外声明“index”变量。 (2认同)