Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the import keyword useful?

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?

like image 539
BanksySan Avatar asked Apr 18 '16 20:04

BanksySan


People also ask

Why is the keyword import used?

The import keyword is used to import a package, class or interface.

What is import keyword Java?

import is a Java keyword. It declares a Java class to use in the code below the import statement. Once a Java class is declared, then the class name can be used in the code without specifying the package the class belongs to. Use the '*' character to declare all the classes belonging to the package.


1 Answers

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 aliased var will not be reflected in the original variable.

source

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.

like image 200
Mike Cluck Avatar answered Oct 10 '22 02:10

Mike Cluck