扩展 DefinitelyTyped 定义的正确方法?(TypeScript v.2.3.4)
经过相当多的研究,我设法将我的接口 IRequestShortcutConfig 与 @types/angular 提供的现有接口合并。我创建了一个包含我的接口的单独文件:
// custom.d.ts
export {}; // Ensure this is treated as a module.
declare module 'angular' {
interface IRequestShortcutConfig {
tracker?: any;
}
}
第一个“特殊之处”是,根据 https://github.com/Microsoft/TypeScript-Handbook/issues/258#issuecomment-213490734 ,我们需要至少有一个顶级导出或导入语句。
你只能在已经是 ES6 模块的情况下增强 ES6 模块。
为什么会这样?
我发现有点困惑的第二件事是,在 DefinitelyTyped 的定义中,接口是这样定义的:
declare namespace angular {
interface IRequestShortcutConfig extends IHttpProviderDefaults {
/**
* {Object.<string|Object>}
* Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified.
*/
params?: any;
/**
* {string|Object}
* Data to be sent as the request message data.
*/
data?: any;
/**
* Timeout in milliseconds, or promise that should abort the request when resolved.
*/
timeout?: number|IPromise<any>;
/**
* See [XMLHttpRequest.responseType]https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype
*/
responseType?: string;
}
}
然而要实际增强带命名空间的接口,我们需要用 declare module 'angular' 来包装接口,而不是 declare namespace angular,正如我在本问题开头的文件 custom.d.ts 中所示。
来自 TypeScript 手册的引用:
关于术语的说明:需要注意的是,在 TypeScript 1.5 中,命名已发生变化。“内部模块”现在被称为“命名空间”。“外部模块”现在简单称为“模块”,以与 ECMAScript 2015 的术语保持一致(即 module X { 相当于现在推荐的 namespace X {)。
所以“外部”模块只是一个已经“导入”的模块吗?
它确实有效,但我想知道通过 npm 安装的类型定义(@types)扩展的方式是否正确?