Zoltán Tamási Zoltán Tamási - 1 year ago 80
TypeScript Question

How to apply a type guard for jQuery instance?

I'm trying to apply a type guard for a variable which might be a jQuery instance. However, as

is an interface from
, I can't use it with
. The following code doesn't seem to work, I guess because TS doesn't "know" that being an instance of
means being "an instance" of

var stringOrJQuery: string | JQuery;
if (stringOrJQuery instanceof jQuery) {
// here stringOrJQuery is still string | JQuery

I'm using TS 2.0 beta.

Answer Source

You can check string case:

if(typeof stringOrJQuery === 'string') {
    // string case
else {
    // jquery case case

Alternately, you can determine jQuery object by indirect checks like the ones described in this question's answers, such as:

if(stringOrJQuery.jquery !== undefined) { ... // this is a jQuery object

the jquery field of the jQuery object contains jQuery version and should be defined.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download