[英]Class 'Bar' used before its declaration
I have a class named Bar
: 我有一个名为
Bar
的类:
class Bar {
private readonly foo: string;
constructor() {
this.foo = "foo";
}
}
And in my main file I'm trying to use it like this: 在我的主文件中,我试图像这样使用它:
const bar: Bar = new Bar();
But this line gives me the error: 但是这一行给了我错误:
Class 'Bar' used before its declaration.
在声明之前使用的“ Bar”类。
I can make it a var
and declare it inside a function but I'm looking for a better solution which allows me to declare the bar
as a constant. 我可以将其设为
var
并在函数中声明它,但我正在寻找一种更好的解决方案,该解决方案允许我将bar
声明为常量。
The problem is Typescript compiling the project into a single Javascript file which declares the class after the attempted use. 问题是Typescript将项目编译成单个Javascript文件,该文件在尝试使用后会声明该类。
Altough @Fenton's solution works fine. @Fenton 的解决方案可以正常工作。 There is another:
还有另一种:
Inside tsconfig.json
you can type: 在
tsconfig.json
您可以输入:
"files": [
"libs/Bar.ts",
],
"include": [
"**/*"
]
This will tell Typescript to compile libs/Bar.ts
before the others. 这将告诉Typescript在其他
libs/Bar.ts
之前先编译libs/Bar.ts
You may need to hint to the compiler that the other file is there, although this depends on your IDE as some work this out for themselves. 您可能需要向编译器提示存在另一个文件,尽管这取决于您的IDE,因为有些文件可以自己解决。
///<reference path="./libs/Bar.ts" />
const bar: Bar = new Bar();
This is so ugly... - Jonas W.
太丑了...-乔纳斯·W。
My opinion has long been that you should prefer modules, and module loaders over namespaces, and reference comments . 长期以来,我的观点是,您应该更喜欢模块和模块加载器,而不是名称空间和参考注释 。 It has been my opinion since before they were called this , but bear in mind the OP has already made this comment.
自从他们被称为“我”以来,我一直认为,但是请记住,OP已经发表了此评论。
I don't use export or import because the output is a single file targeting es5
我不使用导出或导入,因为输出是针对es5的单个文件
Now it is in fact still possible to achieve a single file output, targeting ES5, even if you write modules with imports, because you can use additional tooling to process the modules into a single file, or you can use a module loader like SystemJS or RequireJS - but we ought to consider how much subjectivity we ought to introduce to an answer; 现在, 它实际上还是有可能实现一个单一的文件输出,瞄准ES5,即使你写的模块,进口,因为你可以使用其他工具的模块处理成一个单一的文件,或者你可以使用一个模块加载像SystemJS或RequireJS-但是我们应该考虑应该为答案引入多少主观性; and how appropriate it may be to attempt to convert every person with a question to our own workflow.
以及尝试将每个有问题的人转换为我们自己的工作流程的适当程度。
For example, I disagree with bundling an entire program into a single script file*, when it could be better delivered by leaving the modules intact - but I don't try to answer every webpack question with that. 例如, 我不同意将整个程序捆绑到一个脚本文件中*,而可以通过保持模块完好而更好地交付它-但我不会尝试以此回答每个webpack问题。
* I disagree to the extent that bundling is currently heralded as being a "best practice", based on dated premises. *我不同意当前基于过时前提的捆绑销售被认为是“最佳实践”的程度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.