简体   繁体   中英

Typescript Union Types

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?

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 (eg https://code.jquery.com/jquery-2.1.4.js ) applies (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM