1

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

in the else block, is it necessary to cast $items to JQuery (i.e.: var $item = $items as JQuery) or will this be automatically inferred by typescript?
No, you don't need to cast the variable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.