Express and Typescript - Error.stack and Error.status properties do not exist Express and Typescript - Error.stack and Error.status properties do not exist express express

Express and Typescript - Error.stack and Error.status properties do not exist


Extend global Error

You can tell TypeScript that for your use case Error might have a status on it:

interface Error {    status?: number;}

So you get:

interface Error {    status?: number;}var err = new Error('Not Found');err.status = 404;

Alternative

Put the status on the res and send the err. For Example:

// catch 404 and forward to error handlerapp.use(function (req, res, next) {    var err = new Error('Not Found');    res.status(404); // using response here    next(err);});


The best way in my opinion, is not to disable type checks by setting the error to any, or creating a new Error type, since one already exists in @types/node.

Instead, you should extend that error type:

interface ResponseError extends Error {  status?: number;}


You put the error code on the response...

app.use(function (req, res, next) {    var err = new Error('Not Found');    res.status(404)    next(err);});