[英]Typescript declaration merging: override?
Is there a way to "override" when doing declartion merge, eg: 在进行声明合并时有没有办法“覆盖”,例如:
app.ts (express + nodejs): app.ts(express + nodejs):
import * as express from 'express';
var app = express();
app.use(function(req, res, next) {
console.log(req.headers.accept);
});
This fails with error: 这失败了,错误:
error TS2339: Property 'accept' does not exist on type '{ [key: string]: string; }'.
Because in express.d.ts headers are declared like this: 因为在express.d.ts标头中声明如下:
headers: { [key: string]: string; };
So what i've tried to do, is create a definition of 'accept' : 所以我试图做的是创建'接受'的定义:
declare module Express {
export interface Headers {
accept: String
}
export interface Request {
headers: Headers
}
}
But that does not work also (i can only add new members, not override them, right?): 但这也不起作用(我只能添加新成员,而不是覆盖它们,对吧?):
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; }'.
So the only way to overcome this is change notation to: 所以解决这个问题的唯一方法是改变符号:
req.headers.accept -> req.headers['accept']
Or i somehow can "redeclare" the headers property? 或者我可以“重新声明”标题属性?
In Express, you can use the accepts
method ( accepts documentation ): 在Express中,您可以使用
accepts
方法( 接受文档 ):
if (req.accepts('json')) { //...
Or if you want them all, they are available as: 或者如果你想要它们,它们可用作:
console.log(req.accepted);
To get other headers, use the get
method ( get method documentation ) 要获取其他标头,请使用
get
方法( 获取方法文档 )
req.get('Content-Type');
These are all included the the type definition for Express on Definitely Typed . 这些都包含在Express on Definitely Typed的类型定义中 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.