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

282
Visualizações
throw new TypeError or throw TypeError

In Typescript is there a difference in using new or not when throwing (TypeError)?

throw TypeError("some error here")

and

throw new TypeError("some error here")

?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This is more a JavaScript question than a TypeScript question. No, there's no difference in the technical result, both create new TypeError objects (details in the specification). When called normally (not via new), both Error and the various "native" error constructors (TypeError, ReferenceError, etc.) will perform a new call (a construct call) instead of a normal call.

const e1 = new TypeError("Error message here");
console.log(e1 instanceof TypeError); // true
console.log(e1.message);              // Error message here
const e2 = TypeError("Error message here");
console.log(e2 instanceof TypeError); // true
console.log(e2.message);              // Error message here

Here's that same code on the TypeScript playground, showing that TypeScript sees both e1 and e2 as being of type TypeError. The reason for that is that TypeScript's primary definition for TypeError (in lib.es5.d.ts) looks like this:

interface TypeError extends Error {
}

interface TypeErrorConstructor extends ErrorConstructor {
    new(message?: string): TypeError;
    (message?: string): TypeError;
    readonly prototype: TypeError;
}

declare var TypeError: TypeErrorConstructor;

As you can see, it has both new(message?: string): TypeError; (constructor call returning TypeError) and (message?: string): TypeError; (normal call returning TypeError).


Subjectively, using new is clearer to readers of the code, highlighting that a new object is being created.

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