我试图在我的Typescript类中避免双重声明。
在我写这样的课之前:
module ModuleName {
export class ClassName {
public method: () => void;
constructor(
private dependency: any ) {
this.method = () => {
dependency.someUse();
};
}
}
}
但是方法类型的声明(这里public method: () => void;
)看起来没用,特别是当你已经有一个声明它的接口时。所以我想写:
module ModuleName {
export class ClassName {
constructor(
private dependency: any ) { }
public method = () => {
this.dependency.someUse();
};
}
}
注意:为了避免警告variable XXX used before declaration
,我们必须将方法放在构造函数之后。
但是现在如果我们在构造函数中使用我们的方法,我们再次获得有关此方法的警告:
module ModuleName {
export class ClassName {
constructor(
private dependency: any ) {
this.method(); // warning here
}
public method = () => {
this.dependency.someUse();
};
}
}
所以,我的问题是:我们应该如何正确地编写课程?
注意:由于打字稿编译器更正了声明的顺序,这不是什么大问题,我只是想知道是否可以在没有双重声明和警告的情况下编写类。 的
答案 0 :(得分:2)
这听起来像TSLint的错误。您是否使用WebEssentials进行任何更改?
您可能希望禁用此规则,因为您说它看起来很糟糕。 WebEssentials从您的用户主目录(tslint.json
)加载%userprofile%
。您应该能够在那里找到tslint.json文件。您可以在此处启用/禁用规则。
听起来以下规则中存在错误
之前不允许使用变量
no-use-before-declare
在声明`
您可以通过添加(或更改)配置来禁用此规则:
"no-use-before-declare": false
有关tslint及其规则的更多信息,请访问:https://github.com/palantir/tslint/
答案 1 :(得分:0)
最后我认为删除此警告是一个坏主意,因为在某些情况下它可能非常有用。
但我找到了如何解决我的问题: 如果我们将构造函数移动到类的末尾,我们就不再有警告了:
module ModuleName {
export class ClassName {
public method = () => {
this.dependency.someUse();
};
constructor(
private dependency: any ) {
this.method();
}
}
}
如果我们看一下生成的JS,它更容易理解发生了什么:构造函数的参数仍然放在生成函数的开头:
var ModuleName;
(function (ModuleName) {
var ClassName = (function () {
function ClassName(dependency) {
var _this = this;
this.dependency = dependency;
this.method = function () {
_this.dependency.someUse();
};
this.method();
}
return ClassName;
})();
ModuleName.ClassName = ClassName;
})(ModuleName || (ModuleName = {}));
答案 2 :(得分:-2)
导致错误variable XXX used before declaration
是因为将类方法声明为类属性。
而不是像这样声明你的方法:
public method = () => {
声明如下:
public method() {
所以你的课程看起来像这样:
module ModuleName {
export class ClassName {
constructor(private dependency: any ) { }
public method() {
this.dependency.someUse();
}
}
}