Options
All
  • Public
  • Public/Protected
  • All
Menu

Module is/instanceOf

Index

References

Functions

References

Renames and re-exports isInstanceOf

Functions

  • isInstanceOf<T>(target: unknown, declaration: Constructor<T>, loose?: boolean): target is T
  • Performs a loose instance check by comparing class names up the prototype chain if instanceof initially fails. To disable this loose check, pass false as the 3rd argument.

    import { isInstanceOf } from 'tily/is/instanceOf';

    if (isInstanceOf(error, Error)) {
    console.log(error.stack);
    }

    Generics can be used to type the object being checked. This will default to the declaration passed to the 2nd argument.

    isInstanceOf<ParseError>(error, Error);
    

    Loose checks can be useful if multiple copies of the same class declaration exists in the module tree. For example, multiple versions of the same package are imported.

    example
     isInstanceOf(undefined, Foo);           //=> false
    isInstanceOf(null, Foo); //=> false

    class Foo {}
    class Bar {}

    isInstanceOf(new Foo(), Foo); //=> true
    isInstanceOf(new Bar(), Foo); //=> false

    class Baz {}
    Object.defineProperty(Baz, 'name', { value: 'Foo' });

    isInstanceOf(new Baz(), Foo); //=> true
    isInstanceOf(new Baz(), Foo, false); //=> false

    Type parameters

    • T = unknown

    Parameters

    • target: unknown

      The object to check

    • declaration: Constructor<T>

      The constructor

    • loose: boolean = true

      Whether use loose checks. Default is true.

    Returns target is T

Generated using TypeDoc