hptsk hptsk - 1 month ago 21
Javascript Question

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

I'm trying to convert an existing node.js project from javascript to typescript. I've been using the default 404 error catcher from the Visual Studio Express 4 template:

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


However, I'm getting the following error message:
Property 'status' does not exist on type 'Error'.

I get a similar message if I try and invoke the Error's .stack property:
Property 'stack' does not exist on type 'Error'.

Does anyone know what's going on here?

Edit: Steve Fenton points out that I could just put the error status on the response object. However, my error handling mechanism uses a two-step process:


  1. Create the 404 error and set it's status

  2. Hand it on to the following generic handler:

    app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
    message: err.message,
    error: {}
    });
    });



So the error status is first set on the Error object, then read back by the error handler to decide how to handle the error.

Answer

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;

However I have to say that your express code is non-idiomatic, but TypeScript can understand it, if you tell it about it.