I am building my first TypeScript Express project and am having difficulty configuring the app.ts file. I imported all of the required types from @types/node and @types/express and have applied them to the functions below:
import { NextFunction } from "express";
import { Request, Response } from "express";
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req: Request, res: Response, next: NextFunction) {
next(createError(404));
});
// error handler
app.use(function(err: Error, req: Request, res: Response, next: NextFunction) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
The issue I am having now is that I want to render an error page with the status stored on the error object. TypeScript is flagging up an error on status of this row:
res.status(err.status || 500);
Here is the error:
Property 'status' does not exist on type 'Error'.ts(2339)
I attempted to extend the Error type which I imported from @types/express, but I couldn't get this to work either.
interface ErrorStatus extends Error {
status: number;
}
I couldn't find anybody with a similar issue for what I imagine is a fairly common error when utilising the Express-generator package. Any help would be highly appreciated, thank you.