'type' 语句的正确位置在哪里?
Where is the correct place for 'type' statements?
我最近一直在玩 TypeScript 1.4,我想了解 type aliases via the type
keyword 的正确用法。为了添加一些上下文,我有一堆我以这种方式构建的 TypeScript 文件:
module A.B.C {
export class MyClass {
// ...
}
}
为了避免不得不使用 var thing:A.B.C.MyClass
,我一直在尝试以各种方式使用 type
关键字,每种方式都有自己的问题:
文件顶部。
我所做的第一次尝试是将这些语句放在文件的顶部,在 module
语句之上:
type MyClass = A.B.C.MyClass;
module D.E {
// Yada yada.
}
然而,一旦我在另一个文件中执行此操作,编译器不喜欢我在两个文件中两次使用相同的语句。
在模块内。
我的下一个想法是将语句放在模块定义中:
module D.E {
type MyClass = A.B.C.MyClass;
// ...
}
这在一段时间内运作良好,但后来我 运行 在尝试将 new MyClass
分配给 class 成员时遇到某种歧义错误。例如:
module D.E {
type MyClass = A.B.C.MyClass;
export class AnotherClass {
private thing:MyClass;
constructor() {
this.thing = new MyClass(); // Error is here.
}
}
}
结果:
Assigned expression type D.E.MyClass
in not assignable to type A.B.C.MyClass
显然我完全以错误的方式接近这个。实现我想要做的事情的正确方法是什么?我怀疑我的第一次尝试更接近正确,那些 type
语句只属于某个地方的单个文件?
However once I did this in another file, the compiler didn't like that I had the same statement twice across two files.
那就不要重复了。在 globals.ts
这样的地方做一次就好了
顺便说一句:我建议你不要使用内部模块(heres why) and I recommend you use external modules: https://www.youtube.com/watch?v=KDrWLMUY0R0
更新
不要将 type
用于您要在 code 中使用的内容。仅将 type
用于 type annotation
声明 space 中的内容。
要为 类 添加别名,您需要使用 var
。如下所示:
module a.b {
export class Foo {
constructor(a, b) {
}
}
}
var Bar = a.b.Foo;
var b = new Bar(1, 2);
我再一次警告你使用 --out
的危险。
我最近一直在玩 TypeScript 1.4,我想了解 type aliases via the type
keyword 的正确用法。为了添加一些上下文,我有一堆我以这种方式构建的 TypeScript 文件:
module A.B.C {
export class MyClass {
// ...
}
}
为了避免不得不使用 var thing:A.B.C.MyClass
,我一直在尝试以各种方式使用 type
关键字,每种方式都有自己的问题:
文件顶部。
我所做的第一次尝试是将这些语句放在文件的顶部,在 module
语句之上:
type MyClass = A.B.C.MyClass;
module D.E {
// Yada yada.
}
然而,一旦我在另一个文件中执行此操作,编译器不喜欢我在两个文件中两次使用相同的语句。
在模块内。
我的下一个想法是将语句放在模块定义中:
module D.E {
type MyClass = A.B.C.MyClass;
// ...
}
这在一段时间内运作良好,但后来我 运行 在尝试将 new MyClass
分配给 class 成员时遇到某种歧义错误。例如:
module D.E {
type MyClass = A.B.C.MyClass;
export class AnotherClass {
private thing:MyClass;
constructor() {
this.thing = new MyClass(); // Error is here.
}
}
}
结果:
Assigned expression type
D.E.MyClass
in not assignable to typeA.B.C.MyClass
显然我完全以错误的方式接近这个。实现我想要做的事情的正确方法是什么?我怀疑我的第一次尝试更接近正确,那些 type
语句只属于某个地方的单个文件?
However once I did this in another file, the compiler didn't like that I had the same statement twice across two files.
那就不要重复了。在 globals.ts
顺便说一句:我建议你不要使用内部模块(heres why) and I recommend you use external modules: https://www.youtube.com/watch?v=KDrWLMUY0R0
更新
不要将 type
用于您要在 code 中使用的内容。仅将 type
用于 type annotation
声明 space 中的内容。
要为 类 添加别名,您需要使用 var
。如下所示:
module a.b {
export class Foo {
constructor(a, b) {
}
}
}
var Bar = a.b.Foo;
var b = new Bar(1, 2);
我再一次警告你使用 --out
的危险。