TypeScript:如何使现有命名空间全局化?

我正在尝试停止使用TSD在通过全局变量使用许多库的项目中获取类型定义(如果这很重要,则在tsconfig.json中使用outFile选项).特别是,它以这种方式使用Moment库. Moment提供
its own type definitions作为NPM包的一部分.但是,这些定义不会在全局范围内声明任何内容.请注意,moment既是moment.MomentStatic类型的全局变量,也是类型命名空间.使用NPM包,我如何以这样的方式扩展全局范围:一切都开始工作,因为它现在使用从TSD获得的旧类型定义?也就是说,在全局,任何文件中,作为变量和类型命名空间的时刻都应该是可用的.基本上,我想要的是这些方面:

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.例子:

>将与globals / 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;
点赞