shelving/util/classmodule

Type utilities and runtime helpers for working with class constructors and instances. Useful when you need to check whether a value is a constructor, whether an object is an instance of a particular class, or when you need to inspect property descriptors.

Usage

Checking constructors and instances

ts
import { isConstructor, isInstance, assertInstance } from "shelving/util";

isConstructor(class Foo {});    // true
isConstructor(function () {});  // false — regular function, not a class

isInstance(new Map(), Map);     // true
isInstance({}, Map);            // false

assertInstance(value, MyClass); // throws RequiredError if not an instance

Inspecting property descriptors

ts
import { getGetter, getSetter } from "shelving/util";

class MyClass {
  get name() { return this._name; }
  set name(v) { this._name = v; }
}

const obj = new MyClass();
const getter = getGetter(obj, "name"); // the getter function, or undefined
const setter = getSetter(obj, "name"); // the setter function, or undefined

Functions

Go

isConstructor()function

Is a given value a class constructor?

isConstructor(value: unknown): value is AnyConstructor
Go

isInstance()function

Is a value an instance of a class?

isInstance(value: unknown, type: Class<T>): value is T
Go

assertInstance()function

Assert that a value is an instance of something.

assertInstance(value: unknown, type: Class<T>): asserts value is T
Go

getGetter()function

Get the 'getter' function for a given property, or undefined if it doesn't exist.

getGetter(obj: T, prop: K): ((this: T) => T[K]) | undefined
Go

getSetter()function

Get the 'setter' function for a given property, or undefined if it doesn't exist.

getSetter(obj: T, prop: K): ((this: T, value: T[K]) => void) | undefined

Types

Go

Constructortype

Class that has a public constructor() function.

new (...args: A) => T
Go

AnyConstructortype

Any class constructor (designed for use with extends AnyConstructor guards).

new (...args: any) => any
Go

Classtype

Class prototype that can be used with instanceof.

new (...args: any) => T