Typescript错误:“元素隐式具有'any'类型,因为类型'Error'没有索引签名”

时间:2018-07-22 06:27:34

标签: typescript

代码在这里:

app.use((req: express.Request,
         res: express.Response, next: express.NextFunction) => {
  let err = new Error('Not Found');
  err['status'] = 404;
  next(err);
});

错误在这里:

src/server.ts(23,3): error TS7017: Element implicitly has an 'any' type because type 'Error' has no index signature.

由于错误是默认的全局类型,所以我不知道如何处理错误。

1 个答案:

答案 0 :(得分:0)

Typescript将Error视为任何错误,您正尝试传递索引。尝试此操作

 app.use((req: express.Request, res: express.Response, next: Function) => {
                let err: any = new Error('Not Found');
                err.status = 404;
                next(err);
            });
            let error = new ectrl.ErrorController();
            app.use('*', error.errorAction);
            return app;
}

您的ectrl在哪里

export module Controller {
    export class ErrorController extends ctrl.Controller {

        constructor() {
            super();
        }

        errorAction(err: any, req: Request, res: Response, next: Function) {
            let data = {
                message: err.message,
                error: err,
                title: err.message,
                layout: path.join(__dirname, '..', 'views', 'layouts', 'layout.hbs')
            };
            res.status(err.status || 500);
            res.render('error/error', data);
        }
    }
}