DefinitelyTyped / DefinitelyTyped

The repository for high quality TypeScript type definitions.
Other
48.29k stars 30.07k forks source link

[@types/jquery] Can't narrow union of JQuery type with $ global #52228

Open kinging123 opened 3 years ago

kinging123 commented 3 years ago

Consider this code:

function test(jqElementOrNodeList: JQuery|NodeList) {
  if (jqElementOrNodeList instanceof $) {
    jqElementOrNodeList.toArray(); // <---- Gives an error:  Property 'toArray' does not exist on type 'NodeList'. ts(2339)
  }
}

The function can receive both a jQuery element ($(".button")) or a DOM NodeList (document.querySelectorAll(".button")). The if statement should act as a narrowing of the union type JQuery|NodeList, and narrow it down to the JQuery type, but because the const $ is of type JQueryStatic, the narrowing doesn't work.

The variable $.fn is of the right type, JQuery, but that gives a different error:

if (jqElementOrNodeList instanceof $.fn) { // The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type. ts(2359)

How can I achieve the narrowing of the union that I need? It seems to me like a very popular usage. Thanks!

Link to playground

Definitions by: @leonard-thieu @borisyankov @choffmeister @Steve-Fenton @Diullei @tasoili @jasons-novaleaf @seanski @Guuz @ksummerlin @basarat @nwolverson @derekcicerone @AndrewGaspar @seikichi @benjaminjackman @s093294 @JoshStrobl @johnnyreilly @DickvdBrink @King2500 @terrymun @martin-badin

BlindChickens commented 3 years ago

@kinging123 I am having the same issue. Did you have any luck at all?