为什么我要在命名空间中保留一个类型,而不是直接导出它。
我可以这样做的例子
export interface Document {
first_name: string
status: Document.DocumentStatus
}
export namespace Document {
export type DocumentStatus = 'active' | 'inactive'
}
但是我可以通过使用命名空间获得相同的结果
export interface Document {
first_name: string
status: DocumentStatus
}
export type DocumentStatus = 'active' | 'inactive'
在此上下文中使用命名空间有什么优势?
根据我的经验,命名空间有助于理清接口的目的,尤其是当接口开始堆积时。
例如
Document.Status
Document.Content
Document.Owner
Person.Name
Person.Status
Person.Address
TypeScriptnamespace
(以前module
,称为"内部模块"(早于 ES 模块import
/export
语法,现在基本上已经过时了。使用 ES 模块时,命名空间的使用通常被认为是多余的。如果需要,您仍然可以将namespace
用于组织目的,但这在很大程度上是个人选择。请注意,对于 ES 模块,您仍然可以作为命名空间导入,即import * as Document from "./Document"
因此使用Document.Status
等引用不依赖于使用namespace
。归根结底,这实际上只是一个组织的选择。