打字稿可以导出功能吗?

新手上路,请多包涵

是否可以从打字稿模块导出一个简单的函数?

这不是为我编译的。

 module SayHi {
    export function() {
    console.log("Hi");
  }
}
new SayHi();

这个工作项 似乎暗示你不能但没有直截了当地说出来。不可能吗?

原文由 George Mauer 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 543
2 个回答

在那个例子中很难说出你要做什么。 exports = 是关于从 外部 模块导出,但您链接的代码示例是一个 内部 模块。

经验法则:如果你写 module foo { ... } ,你正在写一个内部模块;如果您在文件的顶层编写 export something something ,那么您正在编写一个外部模块。你实际上在顶层写 export module foo 有点罕见(从那时起你会双重嵌套这个名字),你会写 module foo 更罕见在具有顶级导出的文件中(因为 foo 不会在外部可见)。

以下事情是有道理的(每个场景都由水平规则描绘):


 // An internal module named SayHi with an exported function 'foo'
module SayHi {
    export function foo() {
       console.log("Hi");
    }

    export class bar { }
}

// N.B. this line could be in another file that has a
// <reference> tag to the file that has 'module SayHi' in it
SayHi.foo();
var b = new SayHi.bar();


文件1.ts

 // This *file* is an external module because it has a top-level 'export'
export function foo() {
    console.log('hi');
}

export class bar { }

文件2.ts

 // This file is also an external module because it has an 'import' declaration
import f1 = module('file1');
f1.foo();
var b = new f1.bar();


文件1.ts

 // This will only work in 0.9.0+. This file is an external
// module because it has a top-level 'export'
function f() { }
function g() { }
export = { alpha: f, beta: g };

文件2.ts

 // This file is also an external module because it has an 'import' declaration
import f1 = require('file1');
f1.alpha(); // invokes f
f1.beta(); // invokes g

原文由 Ryan Cavanaugh 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果您将其用于 Angular,则通过命名导出导出函数。如:

 function someFunc(){}

export { someFunc as someFuncName }

否则,Angular 会抱怨对象不是函数。

编辑:我现在使用 angular 11,这不再需要了。所以 export function(){ ...}

原文由 Eli 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题