Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't use $('.foo').on('click', '.bar', with jQuery and TypeScript

I am using TypeScript and jQuery in a project and I need to use jQuery's on to listen to an event:

const $previewListWrp: jQuery<HTMLElement> = $('.js-preview-list-wrp').first();

$previewListWrp.on('click', '.btn-action.remove', (evt: Event): void => {
  let $box: JQuery<HTMLElement> = $(evt.target).closest('.js-preview-wrp');
  console.log($box.data());
});

However, I get the error

Argument of type '"click"' is not assignable to parameter of type 'PlainObject void> | EventHandlerBase

Just started a new project and installed the latest versions of TypeScript, jQuery and @types/jQuery.

enter image description here

like image 532
Fernando Basso Avatar asked Oct 21 '17 11:10

Fernando Basso


2 Answers

try changing evt: EventTarget to evt: JQuery.Event

like image 192
Feng Avatar answered Nov 04 '22 15:11

Feng


You could use the alternative signature of the on method, in which the first argument is indeed an object, and do:

$previewListWrp.on({
    'click': (evt: EventTarget): void => {
        console.log(evt);
    }
}, '.btn-action.remove');
like image 38
trincot Avatar answered Nov 04 '22 13:11

trincot