【问题标题】:Can I import a TypeScript class from my own module to global?我可以将 TypeScript 类从我自己的模块导入到全局吗?
【发布时间】:2014-09-11 17:46:13
【问题描述】:

我在一个模块中有一个类。

module Foo {
    export class Bar {

    } 

    /* Some more interfaces and classes to be used only in this module */
}
var bar = new Foo.Bar();

这个类是一个库,我不希望其他用户编写 Foo.Bar 而只是 Bar 来使用我的 Bar 类:

var bar = new Bar();

我可以通过定义一个新变量 Bar 来做到这一点。

var Bar = Foo.Bar;

var bar = new Bar();

但是,现在我有一个问题。我不能将 Bar 用作 TypeScript 类型标识符。

function something(bar: Bar) { // Compiler: Could not find symbol 'Bar'.

}

我也可以通过定义一个扩展 Foo.Bar 的新类来解决这个问题。

class Bar extends Foo.Bar {

}

var bar = new Bar();
function something(bar: Bar) {

}

但是,生成的 Bar 类与 Foo.Bar 并不完全相同,因为 Bar === Foo.BarBar.prototype === Foo.Bar.prototype 都返回 false

我试图找到一种使用 TypeScript 模块功能(例如 import 和 require)的方法,但我似乎无法使用它们。有什么好的方法可以将我的 Bar 类公开给全局吗?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    我不确定你是否想要/需要一个模块,只需导出类:

    class Bar {
       x: number;
    }
    
    /* Some more interfaces and classes to be used only in this module */
    
    export = Bar;
    

    然后在消费代码中:

    import Bar = require('./Bar');
    var bar = new Bar();
    

    【讨论】:

    • 这种方法似乎需要用户使用'require'。这不是问题,但我更喜欢让事情变得简单,import Bar = Foo.Bar 正是我想要的!谢谢你的回答:)
    【解决方案2】:

    代替

    interface Bar extends Foo.Bar {
    }
    var Bar = Foo.Bar;
    

    你可以这样做:

    import Bar = Foo.Bar;
    

    完整示例:

    module Foo {
        export class Bar {
            x: number
        } 
    
        /* Some more interfaces and classes to be used only in this module */
    }
    
    import Bar = Foo.Bar;
    
    var bar = new Bar();
    function something(bar: Bar) {
    
    }
    

    【讨论】:

    • 简单多了!这就是我要的。非常感谢!
    • 糟糕。生成的 d.ts 文件现在不包含 Bar 作为全局类对象。嗯……
    • d.ts 问题似乎在新编译器中得到修复。请参阅:github.com/Microsoft/TypeScript/issues/346 任何使用当前版本 1.1 编译器的人都应自行在 d.ts 文件中添加 import Bar = Foo.Bar; 行。
    【解决方案3】:

    事实证明这是按预期工作的。

    module Foo {
        export class Bar {
            x: number
        } 
    
        /* Some more interfaces and classes to be used only in this module */
    }
    interface Bar extends Foo.Bar {
    }
    var Bar = Foo.Bar;
    
    var bar = new Bar();
    function something(bar: Bar) {
    
    }
    

    谢谢!

    【讨论】:

      猜你喜欢
      • 2019-12-24
      • 2019-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-30
      • 2017-08-20
      • 2018-08-19
      • 2016-07-20
      相关资源
      最近更新 更多