打字稿:如何使现有的名称空间全局



我正在尝试停止使用TSD在项目中通过全局变量使用许多诽谤的项目中获取类型定义(如果这很重要,则在tsconfig.json中使用outFile选项)。特别是,它以这种方式使用了时刻库。Moment作为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'

有解决方法吗?

回答我自己的问题。最后,我在使用Globals和outFile的老式项目中找到了一种增强库键入的方法。我们需要每个库的单独的.d.ts。示例:

  1. 将与Globals/UMD的兼容性添加到MONM.JS。要保持与Typescript 1.X兼容,MOMM的类型定义不包括export as namespace行。.d.ts文件(命名为augment.moment.d.ts),可以解决此问题:

    import * as moment from 'moment';
    export as namespace moment;
    export = moment; 
    
  2. 增强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;
    

最新更新