You can only use instanceof
on a constructor value.
That means it must be a constructor value as opposed to just any old object. TypeScript only requires the constructor
property of a class to be a Function
, so at the very least you need to specify that C extends Function
. If you want to be safer, restrict C
to actual constructor functions whose singatures are like new(...args: any[])=>any
.
It also means it must be a constructor value as opposed to its type. The value is clss
, and its type is C
. As pointed out by @vu1p3n0x, you should writeinstanceof clss
. You can't write instanceof C
, since C
is just a type and it doesn't even exist at runtime.
Putting that together:
function instanceOf<T, C extends new (...args: any[]) => any>(value: T, clss: C): boolean {
return value instanceof clss;
}
As an aside, note that in JavaScript value instanceof clss
evaluates either true
or false
. So you can just return it instead of checking it with if
.
Hope that helps; good luck!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…