首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在typescript中导出函数

在 TypeScript 中,可以通过 export 关键字将函数导出,以便在其他模块中使用。以下是几种常见的导出函数的方法:

方法 1:直接导出函数

代码语言:javascript
复制
// myFunction.ts
export function myFunction() {
  console.log('This is my function.');
}

然后在其他模块中导入并使用它:

代码语言:javascript
复制
// anotherModule.ts
import { myFunction } from './myFunction';

myFunction(); // 输出: This is my function.

方法 2:导出函数作为默认导出

代码语言:javascript
复制
// myFunction.ts
function myFunction() {
  console.log('This is my function.');
}

export default myFunction;

然后在其他模块中导入并使用它:

代码语言:javascript
复制
// anotherModule.ts
import myFunction from './myFunction';

myLinkButton.addEventListener('click', myFunction); // 输出: This is my function.

方法 3:在一个模块中导出多个函数

代码语言:javascript
复制
// myFunctions.ts
export function function1() {
  console.log('This is function 1.');
}

export function function2() {
  console.log('This is function 2.');
}

然后在其他模块中导入并使用它们:

代码语言:javascript
复制
// anotherModule.ts
import { function1, function2 } from './myFunctions';

function1(); // 输出: This is function 1.
function2(); // 输出: This is function 2.

方法 4:使用命名空间导出函数

代码语言:javascript
复制
// myFunctions.ts
namespace MyFunctions {
  export function function1() {
    console.log('This is function 1.');
  }

  export function function2() {
    console.log('This is function 2.');
  }
}

export default MyFunctions;

然后在其他模块中导入并使用它们:

代码语言:javascript
复制
// anotherModule.ts
import MyFunctions from './myFunctions';

MyFunctions.function1(); // 输出: This is function 1.
MyFunctions.function2(); // 输出: This is function 2.
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券