TypeScript:如何将现有命名空间设为全局?

标签 typescript momentjs typescript-typings definitelytyped tsd

我正在尝试停止使用 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。示例:

  1. 将与全局/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; 
    
  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;
    

关于TypeScript:如何将现有命名空间设为全局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41336330/

相关文章:

typescript - 如何通过属性的存在或不存在来过滤联合

javascript - 在momentjs中将午夜的偏移量干净地转换为时间对象?

Angular 如何在从 API 获取数据时添加加载器动画?

用于导入类型定义而不是主模块的 TypeScript 字符串

Typescript getter 和 setter 错误

javascript - Moment.js isBefore 函数未按预期工作

javascript - 在 JavaScript 中操作视频时间戳

typescript - 如何输入以接口(interface)作为参数的方法

TypeScript:读取对象中值的通用类型

Typescript 模板文字类型循环约束