[英]Is it idiomatic to use namespaces in Typescript?
I am publishing a library that has a few functions.我正在发布一个具有一些功能的库。 One of the functions returns an internal data structure in the library for debugging purposes.
其中一个函数返回库中的内部数据结构以进行调试。 Currently, my type declaration file looks like this:
目前,我的类型声明文件如下所示:
export default function doSomething(): void;
export function __dumpInternalRepresentation(): IR;
interface IR { ... }
interface Foo extends IR { ... }
interface Bar extends IR { ... }
However, I think this will be confusing to users because they will then be able to import IR
, Foo
, and Bar
even though most people shouldn't import those.但是,我认为这会让用户感到困惑,因为他们将能够导入
IR
、 Foo
和Bar
,即使大多数人不应该导入它们。
As such, I am thinking of switching the declaration file to this:因此,我正在考虑将声明文件切换为:
export default function doSomething): void;
export function __dumpInternalRepresentation(): internal.IR;
export namespace internal {
export interface IR { ... }
export interface Foo extends IR { ... }
export interface Bar extends IR { ... }
}
This way, all the internal data structures are hidden inside of internal
.这样,所有内部数据结构都隐藏在
internal
中。
However, I have read that Typescript namespaces are not recommended for newer code.但是,我读过 Typescript 名称空间不推荐用于较新的代码。 If this is the case, what should I do?
如果是这种情况,我该怎么办?
they will then be able to import IR, Foo, and Bar even though most people shouldn't import those.'
他们将能够导入 IR、Foo 和 Bar,即使大多数人不应该导入它们。
It's strange.真奇怪。 Either you want to export or not export a type, why would you care how consumer import it not?
要么你想导出或不导出一个类型,你为什么要关心消费者如何不导入它? You can't control that.
你无法控制它。
Maybe you need this: Creating another module anotherModule.ts也许你需要这个:创建另一个模块 anotherModule.ts
export {doSomething} from 'thismodule'
So when consumer import... form 'anotherModule'
, they won't see IR you want to hide.因此,当消费者
import... form 'anotherModule'
时,他们不会看到您想要隐藏的 IR。 But they can still import {IR} from 'thisModule'
.但他们仍然可以
import {IR} from 'thisModule'
。
Don't use namespace unless you want to organize type hierarchy from multiple projects, where types from different project can be merged into one.除非您想组织来自多个项目的类型层次结构,否则不要使用命名空间,其中来自不同项目的类型可以合并为一个。 I even never tested it.
我什至从未测试过它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.