Typescript声明合并:重写?

有没有办法在做声明合并时“覆盖”,例如:

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; }; 

所以我试图做的是创build一个“接受”的定义:

 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'] 

或者我以某种方式可以“重新声明”标题属性?

在Express中,您可以使用accepts方法( 接受文档 ):

 if (req.accepts('json')) { //... 

或者,如果你想要他们全部,他们是可用的:

 console.log(req.accepted); 

要获得其他头文件,使用get方法( get方法文档 )

 req.get('Content-Type'); 

这些都包括在定义明确键入的types定义 。