如何在Typescript中覆盖属性是不可空的

Node内置的IncomingMessage(参数(req, res, next)中的(req, res, next)types)的DefinitelyTyped定义已将url定义为可空 。 以下是定义文件的剪切部分:

 // @types/node/index.d.ts declare module "http" { export interface IncomingMessage { /** * Only valid for request obtained from http.Server. */ url?: string; } } 

正如注释所说,这是因为这个属性只有在你从http.Server获得这个IncomingMessage的实例时才有效。 在其他用途​​中,它不会存在,因此它是可以空的。

然而,在我的情况下, 我知道我只是从http.Server获得这些实例,所以有点烦人,我不能没有额外的卫兵访问属性。

 import { IncomingMessage, ServerResponse } from 'http'; function someMiddleware(req: IncomingMessage, res: ServerResponse, next: Function) { const myStr: string = req.url; // bzzzt. // Argument of type 'string | undefined' is not // assignable to parameter of type 'string'. } 

可能很好的提及我正在使用strictNullChecks 2.0.3和strictNullChecks ,这在Typescript游乐场上没有启用。

这是问题。 是否有可能覆盖我的应用程序的定义,以便url不可为空?


这是我已经尝试过…将其添加到我的一个文件中:

 declare module 'http' { interface IncomingMessage { url: string; } } 

…但是这是不允许的:“随后的variables声明必须具有相同的types”。 这在文档中有解释。

我至今唯一能想到的就是创build我自己的模块,导入,扩展和导出接口:

 // /src/http.ts import { IncomingMessage as OriginalIM } from 'http'; export interface IncomingMessage extends OriginalIM { url: string; } // src/myapp.ts import { IncomingMessage } from './http'; // <-- local def function someMiddleware(req: IncomingMessage) { const str: string = req.url; // all good } 

所以,这个工作,但似乎是错误的。

所以我find了一个比较简单的解决scheme。

TypeScript 2.0也添加了一个非空断言运算符 : !

 function someMiddleware(req: IncomingMessage) { const str1: string = req.url; // error, can't assign string | undefined to string const str2: string = req.url!; // works } 

在我的情况下,它仍然有点烦人,因为有许多不同的文件需要访问这个属性,所以这个非null断言在许多地方使用。