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 typeJQuery|NodeList, and narrow it down to the JQuery type, but because the const $ is of type JQueryStatic, the narrowing doesn't work.
The variable $.fnis 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!
Consider this code:
The function can receive both a jQuery element (
$(".button")
) or a DOM NodeList (document.querySelectorAll(".button")
). Theif
statement should act as a narrowing of the union typeJQuery|NodeList
, and narrow it down to theJQuery
type, but because the const$
is of typeJQueryStatic
, the narrowing doesn't work.The variable
$.fn
is of the right type,JQuery
, but that gives a different error: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