Aliases in TypeScript
In TypeScript, aliases can be used to simplify or shorten access to types or namespaces. One common use case is when you want to import a specific part of a namespace and assign it a shorter or more convenient name, using the import
statement. This is especially helpful when working with deeply nested namespaces.
Example with Aliases
In this example, we’ll create a Shapes
namespace containing a nested Polygons
namespace. We’ll then use an alias to simplify accessing classes from the Polygons
namespace.
Code Example:
namespace Shapes {
export namespace Polygons {
export class Triangle {}
export class Square {}
}
}
// Create an alias for the Polygons namespace
import polygons = Shapes.Polygons;
// Now, you can use the alias to refer to the classes
let sq = new polygons.Square(); // Same as 'new Shapes.Polygons.Square()'
Explanation:
- Nested namespaces:
Polygons
is a nested namespace withinShapes
. - Alias:
import polygons = Shapes.Polygons;
creates an aliaspolygons
for theShapes.Polygons
namespace. - Usage: You can now use the alias
polygons
to access theSquare
class without needing to fully reference the nested namespace path (Shapes.Polygons.Square
).
This reduces the need to repeatedly use the full namespace path and makes your code cleaner and more concise.