有没有办法超越"在进行声明合并时,例如:
app.ts(express + nodejs):
import * as express from 'express';
var app = express();
app.use(function(req, res, next) {
console.log(req.headers.accept);
});
此操作失败并显示错误:
error TS2339: Property 'accept' does not exist on type '{ [key: string]: string; }'.
因为在express.d.ts标题中声明如下:
headers: { [key: string]: string; };
所以我试图做的是创建一个“接受”的定义。 :
declare module Express {
export interface Headers {
accept: String
}
export interface Request {
headers: Headers
}
}
但这也不起作用(我只能添加新成员,而不是覆盖它们,对吗?):
error TS2430: Interface 'e.Request' incorrectly extends interface 'Express.Request'.
Types of property 'headers' are incompatible.
Type '{ [key: string]: string; }' is not assignable to type 'Headers'.
Property 'accept' is missing in type '{ [key: string]: string; }'.
所以解决这个问题的唯一方法就是改变符号:
req.headers.accept -> req.headers['accept']
或者我可以"重新声明" header属性?
答案 0 :(得分:2)
在Express中,您可以使用accepts
方法(accepts documentation):
if (req.accepts('json')) { //...
或者,如果你想要它们全部,它们可用:
console.log(req.accepted);
要获取其他标头,请使用get
方法(get method documentation)
req.get('Content-Type');
中