Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

147
Views
Differentiate function and constructor in runtime

In TypeScript, I'm writing a function that takes an Error factory as an argument: either a class name or a factory function. Something like the below:


// Alias from class-transformer package
type ClassConstructor<T> = {
  new (...args: any[]): T;
};

function doSomething(value: number, errorFactory: () => Error | ClassConstructor<Error>) {
  if (value === 0) {
    // Zero is not allowed
    if (/* errorFactory is a class constructor */) {
      throw new errorFactory()
    } else {
      throw errorFactory()
    }
  }
}

In the above function, errorFactory can be an Error class, such that the following code works:

doSomething(0, Error);

Or it can be a function that creates an Error:

doSomething(0, () => new Error());

The issue is that ClassConstructor is a TypeScript type, so it doesn't survive compilation to JavaScript.

typeof(Error) is function, and so is typeof(()=>{}).

So how to determine the parameter's type? What should be the test in /* errorFactory is a class constructor */?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

By the above code, I understood you need to invoke the constructor with new, and the function without new.

In the above example, Error actually can be invoked without new, it can be called just by typing:

throw Error(msg); // msg: string = The error message

The code below can be used for testing if the function (or constructor) must be called with new:

// Returns:
// - True if the 'func' must be called with 'new'
// - False if the 'func' can be called without 'new'
function isConstructor(func) {
  try {
    // Invoke without 'new'
    func();
  }
  catch (err) {
    if (/^TypeError:.*?constructor/.test(err.toString())) {
      // The error is about that it isn't a normal function
      return true;
    }
    else {
      // The error isn't about that; let's throw it
      throw new err.constructor(err.toString().substr(err.toString().indexOf(" ") + 1), {cause: err});
    }
  }
  return false;
}

// Let's run some tests
console.log(isConstructor("abc".constructor)); // False
// String() returns empty string; it's not a constructor
console.log(isConstructor(() => {}));          // False
// Arrow function
console.log(isConstructor(class {}));          // True
// This *is* a cliss
console.log(isConstructor(Image));             // True
// Some built-in cannot be invoked without 'new'
console.log(isConstructor(throwErr));          // TypeError: Another error
function throwErr() {
  throw new TypeError("Another error");
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!