JS Built-ins
TypeScriptintermediate

Type Guard β€” isInstance

πŸ“– Usage Example
function isInstance<T>(x: unknown, ctor: new (...a: any[]) => T): x is T {
  return x instanceof ctor
}
isInstance(new Date(), Date)   // β†’ true

A generic isInstance guard uses instanceof with a constructor type to narrow any class.

Type Guards: isInstance

Challenge: Implement isInstance<T>(x: unknown, ctor: new (...args: any[]) => T): x is T β€” a generic instanceof check.

isInstance(new Date(), Date)       // β†’ true
isInstance('hello', Date)          // β†’ false
isInstance(new Error('e'), Error)  // β†’ true
πŸ’‘ Hints (1)
  • β€’ x instanceof ctor is the built-in mechanism for checking prototype chain membership.