我正在尝试停止使用 TSD 在通过全局变量使用许多库的项目中获取类型定义(outFile
选项在 tsconfig.json
中使用,如果这很重要)。特别是,它以这种方式使用 Moment 库。矩提供its own type definitions作为 NPM 包的一部分。但是,这些定义并未在全局范围内声明任何内容。请注意,moment
既是 moment.MomentStatic
类型的全局变量,也是类型命名空间。使用 NPM 包,我怎样才能扩大全局范围,使一切都开始工作,因为它现在可以使用从 TSD 获得的旧类型定义?即,moment
应该在任何文件中作为变量和类型命名空间在全局范围内可用。基本上,我想要的是这些方面的东西:
import * as _moment from 'moment';
declare global {
const moment: _moment.MomentStatic;
import moment = _moment;
}
这不编译:
[ts] Imports are not permitted in module augmentations. Consider moving them to the enclosing external module.
[ts] Import declaration conflicts with local declaration of 'moment'
有解决办法吗?
最佳答案
回答我自己的问题。最后,我在一个使用全局变量和 outFile
的老式项目中找到了一种增强库类型的方法。我们需要为每个库创建一个单独的 .d.ts
。示例:
将与全局/UMD 的兼容性添加到 Moment.js。为了与 TypeScript 1.x 保持兼容,Moment 的类型定义不包括
export as namespace
行。修复此问题的.d.ts
文件(命名为augment.moment.d.ts
):import * as moment from 'moment'; export as namespace moment; export = moment;
增加 AngularJS 的类型定义。
augment.angular.d.ts
:import * as angular from 'angular'; declare module 'angular' { interface IRootScopeService { $$destroyed: boolean; } } export as namespace angular; export as namespace ng; export = angular;
关于TypeScript:如何将现有命名空间设为全局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41336330/