6

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. 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:

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.

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
2
  • 2
    @Dale Burell -- Would like to know why I can't have a formal gesture of thanks in a question? It's just a bit of nice etiquette and attitude towards fellow developers. Commented Jan 2, 2019 at 2:29
  • meta.stackexchange.com/questions/2950/… Commented Jan 2, 2019 at 2:32

1 Answer 1

9

Array.prototype.indexOf() receives a parameter searchElement and a second optional parameter fromIndex.

Updated answer based on @Pixxl comment to use Array.prototype. findIndex() to get index variable:

const friends: IAddress[];

// assume friends has a few elements...
const index = friends.findIndex((friend: IAddress) => friend.name === 'some name');
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome, I didn't realize index and indexOf are meant for primitive values whereas find and findIndex are meant for more object-like values. I'd also like to suggest changing this answer to one that uses findIndex instead as it accomplishes the same task without needing to declare an index var outside the scope.
Great comment @Pixxl, thank you.. Edidting the answer to use Array.prototoype.findIndex()...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.