Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

148
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda