📎 Webclip
TypeScript's Secret Parallel Universe
The article describes a TypeScript library API built as a nested object from classes spread across folders. Several attempts to re-export a class from inside a namespace fail because each attempt exports only the value side or only the type side.
The solution is to export both a value and a type under the same name. TypeScript keeps an independent type scope, separate from JavaScript’s variable scope, so a class name can be used both as a constructor value and as an instance type.
Reading notes#
- The author wants classes from separate files to appear as a single nested public API such as
API.Output.Console. export Consoleinside a namespace is invalid TypeScript.export Console = ConsoleAliasdoes not resolve the name.export { ConsoleAlias as Console }is not permitted inside a namespace.export const Console = ConsoleAliascompiles, but the typeAPI.Output.Consoleis missing.export type Console = ConsoleAliasmakes the type usable, butnew API.Output.Console()fails.- The working approach is to export both the value and the type.
- TypeScript maintains a type scope that is independent of JavaScript’s value scope.
- A class declaration creates both a value and a type.
- When a class is imported, both the class object and the class type are imported.
export constexports only the value side.export typeexports only the type side.
