I have been playing around with TypeScript 1.4 recently and I am trying to understand the correct usage of type aliases via the type
keyword. To add some context, I have a bunch of TypeScript files which I have structured this way:
module A.B.C {
export class MyClass {
// ...
}
}
And to get around having to use var thing:A.B.C.MyClass
, I have been trying to use the type
keyword in various ways, each with their own problems:
The first attempt I made was placing these statements at the top of the file, above the module
statement:
type MyClass = A.B.C.MyClass;
module D.E {
// Yada yada.
}
However once I did this in another file, the compiler didn't like that I had the same statement twice across two files.
My next thought was to place the statement within the module definition:
module D.E {
type MyClass = A.B.C.MyClass;
// ...
}
This worked well for some time, but then I ran into some kind of ambiguity error when trying to assign a new MyClass
to a class member. For example:
module D.E {
type MyClass = A.B.C.MyClass;
export class AnotherClass {
private thing:MyClass;
constructor() {
this.thing = new MyClass(); // Error is here.
}
}
}
Results in:
Assigned expression type
D.E.MyClass
in not assignable to typeA.B.C.MyClass
Obviously I am approaching this the wrong way entirely. What is the correct way to achieve what I am trying to do? I suspect my first attempt was closer to correct and that those type
statements just belong in a single file somewhere?
However once I did this in another file, the compiler didn't like that I had the same statement twice across two files.
Don't do it twice then. Just do it once in a place like globals.ts
BTW: I recommend you don't use internal modules (heres why) and I recommend you use external modules: https://www.youtube.com/watch?v=KDrWLMUY0R0
Don't use type
for something that you are going to use in code. Use type
only for stuff that is going to be in the type annotation
declaration space.
To alias classes you will need to use var
. This is shown below:
module a.b {
export class Foo {
constructor(a, b) {
}
}
}
var Bar = a.b.Foo;
var b = new Bar(1, 2);
Again I cannot warn you enough of the hazards of using --out
.