Reputation: 136
I am moving from Javascript to Typescript and am trying to create a class method which can take a JQuery object or an array of them. I am trying to use a union type but cannot seem to get the matching to work with the JQuery parameter:
setToGrey($items: JQuery[]|JQuery) {
if ($items instanceof Array) {
for (var i = 0; i < $items.length; i++) {
var $item = $items[i];
this.resetIcon($item);
$item.addClass(CSSClasses.TEXT_MUTED).find("span." + CSSClasses.GLYPHICON).addClass(CSSClasses.ICON_QUESTION_CICLE);
}
} else if ($items instanceof JQuery) {
this.resetIcon($items);
$items.addClass(CSSClasses.TEXT_MUTED).find("span." + CSSClasses.GLYPHICON).addClass(CSSClasses.ICON_QUESTION_CICLE);
}
}
I cannot get the line:
} else if ($items instanceof JQuery) {
to work, the error comes up as Cannot find name 'JQuery'.
I'm not sure where my misunderstanding is. What am I doing wrong?
Upvotes: 1
Views: 380
Reputation: 28648
You can simply use Array.isArray()
if (Array.isArray($items)) {
// ...
} else {
// ...
}
Please note that the types in the following signature
setToGrey($items: JQuery[]|JQuery) {
are only available at compile time. Whereas instanceof
from
if ($items instanceof JQuery) {
is a run-time check where the content of your jQuery version (e.g. https://code.jquery.com/jquery-2.1.4.js) applies (i.e. jQuery
- notice the casings).
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/jquery/jquery.d.ts#L1154 definition file defines interface JQuery
(again notice the casings) which is available only in compile time.
Upvotes: 1