Reputation: 28510
In typescript I can import another module\namespace like so:
namespace Shapes2 {
import shapes = Shapes;
var bar = new shapes.Bar();
}
However, I can just as easily refer to the namespace directly.
namespace Shapes3{
var shapes = Shapes;
var bar = new shapes.Bar();
}
Is import
doing anything useful?
When would I want to type import
rather than var
?
Upvotes: 8
Views: 443
Reputation: 32511
In that specific case, no it's not doing anything useful. That syntax is for creating aliases for namespaces. Your example would be more useful in a situation like this:
namespace Shapes2 {
import Rects = Shapes.Rectangles;
var bar = new Rects.Red();
// Instead of `var bar = new Shapes.Rectangles.Red()`
}
Basically, it's just a way of reducing the amount of typing you do. In a way, it's a substitution for using
in C#. But how does this differ from var
?
This is similar to using
var
, but also works on the type and namespace meanings of the imported symbol. Importantly, for values,import
is a distinct reference from the original symbol, so changes to an aliasedvar
will not be reflected in the original variable.
A good example of this can be found in the spec:
namespace A {
export interface X { s: string }
}
namespace B {
var A = 1;
import Y = A;
}
'Y' is a local alias for the non-instantiated namespace 'A'. If the declaration of 'A' is changed such that 'A' becomes an instantiated namespace, for example by including a variable declaration in 'A', the import statement in 'B' above would be an error because the expression 'A' doesn't reference the namespace instance of namespace 'A'.
When an import statement includes an export modifier, all meanings of the local alias are exported.
Upvotes: 5
Reputation: 14447
From the TypeScript Handbook
Another way that you can simplify working with of namespaces is to use import q = x.y.z to create shorter names for commonly-used objects. Not to be confused with the import x = require("name") syntax used to load modules, this syntax simply creates an alias for the specified symbol. You can use these sorts of imports (commonly referred to as aliases) for any kind of identifier, including objects created from module imports.
Upvotes: 0