[英]Can typescript export a function?
在那个例子中很难说你要做什么。 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
要直接回答您的问题的标题,因为这首先出现在 Google 中:
是的,TypeScript 可以导出函数!
这是 TS 文档的直接引用:
“任何声明(例如变量、函数、类、类型别名或接口)都可以通过添加 export 关键字导出。”
如果您将此用于 Angular,则通过命名导出导出函数。 如:
function someFunc(){}
export { someFunc as someFuncName }
否则,Angular 会抱怨 object 不是函数。
编辑:我现在使用 angular 11,不再需要了。
就我而言,我是这样做的:
module SayHi {
export default () => { console.log("Hi"); }
}
new SayHi();
您也可以将from
关键字与import
一起使用,并直接销毁导出的 object 。
文件1.ts
export const CARS_QUERY = `
{
getAllCars {
model,
make,
picture
}
}
`;
文件2.ts
import { CARS_QUERY } from "file1.ts";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.