@nevware21/ts-utils
    Preparing search index...

    Function isConstructor

    • Checks whether the value is a constructor, a function which can be called with new (like the ECMAScript IsConstructor() operation), without calling it.

      Where there is a Proxy (ES2015+) a Proxy of the value, whose construct trap doesn't call it (or read any of its properties), is called with new, which is only possible for a constructor: a class, a function declaration or expression, a built-in constructor (eg. Array, and also Symbol and BigInt, which are constructors which throw when they are called with new), a bound constructor or a Proxy of one. An arrow function, a method, a generator, an async function or a built-in function which isn't a constructor (eg. Math.max) isn't one.

      On a runtime without Proxy (eg. ES5) instanceof is used, which only reads the function's prototype (for a bound function its target's, and on these runtimes it can't be a getter) and throws a TypeError when it isn't an object. So a function written in JavaScript, a built-in constructor and a bound constructor are constructors, while a built-in function which isn't a constructor (eg. Math.max or Array.prototype.push, which have no prototype), a bound function of one, a host function (eg. IE's alert), an arrow function or a method (on a runtime which has them but no Proxy) isn't, and neither is a generator function (which has a prototype). The only exception is a function written in JavaScript whose prototype has been replaced with a value which isn't an object, which isn't identified as a constructor there. A runtime with Symbol.hasInstance or async generator functions but without Proxy doesn't exist, on one a function's own Symbol.hasInstance would be used and an async generator function (which has a prototype and isn't identified as a generator) would be identified as a constructor.

      Parameters

      • value: any

        The value to check

      Returns value is new (...args: any[]) => any

      true when the value is a constructor, otherwise false

      0.20.0

      isConstructor(Array);                    // true
      isConstructor(class Foo {}); // true
      isConstructor(function () {}); // true
      isConstructor(() => {}); // false
      isConstructor(Math.max); // false
      isConstructor({ method() {} }.method); // false
      isConstructor(function* () {}); // false
      isConstructor(null); // false