TypeScript:如何使现有的命名空间全局化? [英] TypeScript: How can I make an existing namespace global?

查看:763
本文介绍了TypeScript:如何使现有的命名空间全局化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图停止使用TSD在通过全局变量使用许多库的项目中获取类型定义(如果这很重要,请在tsconfig.json中使用outFile选项).特别是,它以这种方式使用Moment库. Moment提供自己的类型定义作为其一部分NPM软件包.但是,这些定义未在全局范围内声明任何内容.请注意,moment既是类型为moment.MomentStatic的全局变量,也是该类型的名称空间.使用NPM软件包,如何以这样的方式扩展全局范围,使一切都可以正常工作,因为现在可以使用从TSD获得的旧类型定义了?即,moment应该在任何文件中作为变量和类型名称空间全局可用.基本上,我想要的是以下几方面的东西:

I'm trying to stop using TSD for obtaining type definitions in a project that uses many libaries via global variables (the outFile option is used in tsconfig.json if this matters). In particular, it uses the Moment library in this way. Moment provides its own type definitions as part of the NPM package. However, these definitions don't declare anything in the global scope. Note that moment is both a global variable of type moment.MomentStatic and a type namespace at that. Using the NPM package, how can I augment the global scope in such a way that everything starts working as it works now with the old type definitions got from TSD? Namely, moment should be available globally, in any file, as both a variable and as a type namespace. Basically, what I want is something along these lines:

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

Answering my own question. Finally I found a way to augment library typings in an old-school project that uses globals and outFile. We need a separate .d.ts for each library. Examples:

  1. 向Moment.js添加与globals/UMD的兼容性.为了与TypeScript 1.x保持兼容,Moment的类型定义不包含export as namespace行.修复此问题的.d.ts文件(命名为augment.moment.d.ts):

  1. Adding compatibility with globals/UMD to Moment.js. To stay compatible with TypeScript 1.x, Moment's type definitions don't include the export as namespace line. A .d.ts file (named, say, augment.moment.d.ts) that fixes this:

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:如何使现有的命名空间全局化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆