Why is the import keyword useful?

In typescript, I can import another module namespace as follows:

namespace Shapes2 { import shapes = Shapes; var bar = new shapes.Bar(); } 

However, I can just as easily access the namespace directly.

 namespace Shapes3{ var shapes = Shapes; var bar = new shapes.Bar(); } 

Is import useful something useful?

When do I want to type import , not var ?

+7
javascript typescript
source share
2 answers

In this particular case, there is nothing useful. This syntax is intended to create aliases for namespaces. Your example would be more useful in such a situation:

 namespace Shapes2 { import Rects = Shapes.Rectangles; var bar = new Rects.Red(); // Instead of `var bar = new Shapes.Rectangles.Red()` } 

Basically, this is just a way to reduce the amount of input you make. In a way, this is a replacement for using in C #. But how is this different from var ?

This is similar to using var , but also works with the type and namespace of the imported character. It is important to note that for values, import is a great reference from the original character, so changes to the var alias will not be reflected in the original variable.

a source

A good example of this can be found in the specification:

 namespace A { export interface X { s: string } } namespace B { var A = 1; import Y = A; } 

"Y" is the local alias for the uninterrupted namespace "A". If the declaration "A" is changed so that "A" becomes an instance of the namespace, for example, by including the variable declaration in "A", the import statement in "B" above will be an error because the expression "A" doesn’t refer to the instance namespace namespace 'A'.

When an import statement includes an export modifier, all values ​​of the local alias are exported.

+5
source share

From TypeScript Reference

Another way to simplify working with namespaces is to use q = xyz imports to create shorter names for common objects . Not to be confused with the syntax import x = require ("name") used to load modules, this syntax simply creates an alias for the specified character . You can use these types of imports (usually called aliases) for any type of identifier, including objects created from the import module.

0
source share

All Articles