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 JQuery
is an interface from jquery.d.ts
, I can't use it with instanceof
. The following code doesn't seem to work, I guess because TS doesn't "know" that being an instance of jQuery
means being "an instance" of JQuery
interface.
var stringOrJQuery: string | JQuery;
...
if (stringOrJQuery instanceof jQuery) {
...
// here stringOrJQuery is still string | JQuery
...
}
I'm using TS 2.0 beta.
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.
上一篇: 从选定的值中获取文本
下一篇: 如何应用jQuery实例的类型警卫?