[英]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.