簡體   English   中英

導出Typescript中的函數集合

[英]Exporting a collection of functions in Typescript

我是Typescript的新手,我花了一段時間搜索各種方法來做到這一點,但是我一直陷於困境。

我想創建一個庫文件,其中只包含我可以導入到任何地方的不相關函數的集合。 在普通的Javascript中,我可以做類似的事情:

let libraryFunctions = {};
libraryFunctions.a = () => {
  return true;
}
module.exports = libraryFunctions;

但是,在Typescript中,我只是抱怨說Property 'a' does not exist on type {} 然后,我看到我可以這樣做:

interface ILibraryFunctions {
  a(): boolean;
};

export class LibraryFunctions implements ILibraryFunctions {
  a = () => {
    return false;
  }
}

但是,創建一個類似乎太過分了(除非我對Typescript的類的理解是錯誤的)。 有人能指出我正確的方向嗎?

謝謝!

在TypeScript中,您只需export內容即可,類似於ES2015模塊(也由babel實現):

export function a() {
  return true;
}

// or alternatively

export const b = () => false

然后,在另一個文件中

import {a, b} from './thatFirstFile';
// or
import * as libraryFunctions from './thatFirstFile';

對於您的特定情況,您不需要實現一個類:

interface ILibraryFunctions {
  a(): boolean;
};

const myLib: ILibraryFunctions = {
  a() { return true; }
};

export default myLib;

就是說,從下面丹尼爾的評論中 ,答案頂部提到的方法是更可取的:

實際上,你不會export default與對象a ,你會直接默認出口a本身。 就是說,您之所以不這樣做,是因為現有工具可以更輕松地從頂級導出中搖晃樹,而不是實際對象。 此外,使用第一種語法時,如果有多個導出,則可以使用ES2015的命名導入語法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM