TypeScript中如何在嵌套命名空间内访问根级同名命名空间?
问题
以下TypeScript代码因嵌套命名空间遮蔽导致编译失败:
namespace A { export type MyType = number } namespace B { const myValue: A.MyType = 6 namespace A { } }
原因是命名空间B内部的namespace A遮蔽了根级的namespace A。请问有没有无需修改任何命名空间名称就能访问根级A的方法?
我曾尝试过以下无效写法:
namespace A { export type MyType = number } namespace A_root = A //<--无效语法 namespace B { const myValue: A_root.MyType = 6 namespace A { } }
如果无法实现,只能给命名空间加后缀(如A_0、A_1等),但这种方式不够优雅。
可行方案
使用全局作用域标识符
globalThis
TypeScript中可通过globalThis直接定位根级命名空间,修改后代码可正常编译:namespace A { export type MyType = number } namespace B { const myValue: globalThis.A.MyType = 6 namespace A { } }该方式无需修改原有命名空间名称,直接通过全局对象绕过内部遮蔽。
提前在根级创建合法别名
你之前的别名写法存在语法错误,正确的别名定义可通过type(针对类型)或import(兼容类型与值空间)实现:
针对类型场景:namespace A { export type MyType = number } // 为根级A的类型创建别名 type A_root = A; namespace B { const myValue: A_root.MyType = 6 namespace A { } }若需同时处理命名空间中的值(如导出变量、函数),可使用
import语句:namespace A { export type MyType = number export const foo = 123; } // 导入根级A并命名为A_root import A_root = A; namespace B { const myValue: A_root.MyType = 6 const bar = A_root.foo; namespace A { } }该方式通过提前在根级定义别名,避开内部命名空间的遮蔽问题,同样无需修改原有命名空间名称。
内容的提问来源于stack exchange,提问作者Corno
相关产品推荐
相关产品推荐

