语法-打字稿可以导出功能吗?
是否可以从打字稿模块中导出简单功能?
这不是为我编译。
module SayHi {
export function() {
console.log("Hi");
}
}
new SayHi();
这个工作项似乎意味着您不能但不能说清楚。 不可能吗
George Mauer asked 2020-08-10T05:34:37Z
4个解决方案
60 votes
在该示例中很难说出要做什么。 module foo { ... }
是关于从外部模块导出的,但是您链接的代码示例是内部模块。
经验法则:如果您编写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();
file1.ts
// This *file* is an external module because it has a top-level 'export'
export function foo() {
console.log('hi');
}
export class bar { }
file2.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();
file1.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 };
file2.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
3 votes
要直接回答您的问题的标题,因为这首先出现在Google中:
是的,TypeScript可以导出函数!
这是TS文档的直接报价:
“可以通过添加export关键字来导出任何声明(例如变量,函数,类,类型别名或接口)。”
参考链接
0 votes
就我而言,我这样做是这样的:
module SayHi {
export default () => { console.log("Hi"); }
}
new SayHi();
0 votes
如果将其用于Angular,则通过命名导出导出函数。 如:
function someFunc(){}
export { someFunc as someFuncName }
否则,Angular会抱怨object不是一个函数。