Converting jQuery .map() method call to TypeScript

962 views Asked by At

I am refactoring some .js files to Typescript.

Referencing https://github.com/DefinitelyTyped/DefinitelyTyped/tree/types-2.0/jquery to resolve jQuery methods.

The source code has several instances of code similar to this:

$("#id").map( (ev)=> {
  return $(ev.target).val();
}) 

The usage suggests that map takes a callback, with ev an event (with a target property), however jQuery.d.ts defines the method as follows:

map(callback: (index: number, domElement: Element) => any): JQuery;

As a result the Typescript compiler barfs, saying

'property target does not exist on type number'

The relevant version of jQuery is 1.7.2

EDIT

Following the answer from @FunStuff, I have modified the code as follows:

.map( (i, el)=> {
  return $(el).val();
})

Which Resharper likes. I am still confused as to how that method signature resolved in Vanilla JS?

1

There are 1 answers

5
Bazinga On BEST ANSWER

Because the first argument is the index and it's type is a number.

$("#id").map((index, element) => {
  console.log(element);
});

map(callback: (index: number, domElement: Element) => any): JQuery;

And watch that the second argument is the current DOM element not the event.

Now it should work.