typescript 打字稿:导出命名空间中的所有函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38168733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:36:58  来源:igfitidea点击:

Typescript: export all functions in a namespace

typescript

提问by zeroin

Lets say I have a typescript file Utilswith a bunch of exported functions:

假设我有一个带有一堆导出函数的打字稿文件Utils

export function utilOne(){}
export function utilTwo(){}

I added index.d.ts file to this folder where I export * from the Utils file:

我将 index.d.ts 文件添加到我从 Utils 文件导出 * 的文件夹中:

export * from './Utils';

In my other classes I'd like to access functions utilOne and utilTwo via utils namespace, like:

在我的其他类中,我想通过 utils 命名空间访问函数 utilOne 和 utilTwo,例如:

utils.utilOne();

I know that I can import it like this:

我知道我可以像这样导入它:

import * as utils from "./Utils";

However, as I will be using utils a lot, I would like to be able to export utils in a namespace, something like:

但是,由于我将大量使用 utils,我希望能够在命名空间中导出 utils,例如:

export {* as utils} from './Utils';   // this doesn't work

and then use:

然后使用:

import * from "./Utils";

However the export {* as utils} doesn't work. I could put all the functions of Utils to a module "utils" and export it, but I am not sure if this is a good practice. Is there a proper way to do this?

但是 export {* as utils} 不起作用。我可以将 Utils 的所有功能放到一个模块“utils”中并将其导出,但我不确定这是否是一个好的做法。有没有合适的方法来做到这一点?

采纳答案by basarat

import * from

进口于

No. Global imports are considered bad practice even in languages that support them. (e.g. python Why is "import *" bad?)

不可以。即使在支持它们的语言中,全局导入也被认为是不好的做法。(例如 python为什么“import *”不好?

JavaScript / TypeScript doesn't support it. After all its pretty useful to see foo.barand know that bar is coming from fooinstead of barand having no clue where bar is coming from (without cloning and analyzing the whole project).

JavaScript / TypeScript 不支持它。毕竟,查看foo.bar和知道 bar 来自foo而不是bar不知道 bar 来自哪里非常有用(无需克隆和分析整个项目)。