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

429
Visualizações
Typescript error when adding property to Error object "Property ... does not exist on type 'Error'"

I'm trying to move to typescript with my Node/Express app. Previously my code was:

//app.js
const error = new Error('Not Found');
error.status = 404;

When I try this:

//app.ts
const error = new Error('Not Found');
error.status = 404; // Property 'status' does not exist on type 'Error'.ts(2339)

I understand from developer.mozilla.org documentation that the Error constructor has the following optional parameters: message, options, fileName, lineNumber - so I guess status shouldn't be permitted? I think I've copied it from a youtube tutorial so I guess it's not actually good practice?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

TypeScript does not allow adding unknown properties. There are ways to define objects with arbitrary keys (e.g. Record).

In this case you could create your own subclass to Error which includes the status property.

class StatusError extends Error {
  status: number | undefined;
}

const e = new StatusError('Not found');
e.status = 404;

You could also add it to the constructor, then you can confidently remove the undefined.

class StatusError extends Error {
  constructor(public status: number, message?: string) {
    super(message)
  }
}

const e = new StatusError(404, 'Not found');
over 4 years ago · Santiago Trujillo Relatório

0

I found in the expressjs.com documentation there is a section on "How do I handle 404 responses?", where they provide this example:

app.use(function (req, res, next) {
  res.status(404).send("Sorry can't find that!")
})

So I've produced this and it has stopped the error:

import express, {NextFunction, Request, Response} from "express";

const app = express();
...

app.use((req: Request, res: Response, next: NextFunction) => {
    res.status(404).send("Sorry can't find that!");
});

export { app };
over 4 years ago · Santiago Trujillo 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