简体   繁体   中英

Converting jQuery .map() method call to TypeScript

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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