我把初始化成员的过程放到一个方法reset()里了,然后在构造函数constructor里调用这个初始化方法,在严格模式下,ts会给出一个没有初始化的错误提示。
情况如下:
代码:
class A extends B {
index: number; // 错误 属性“index”没有初始化表达式,且未在构造函数中明确赋值。
constructor() {
super();
this.reset();
}
reset() {
this.index = 0;
}
add() {
++this.index;
}
}
查看同类问题https://segmentfault.com/q/10...。加入明确赋值断言index!: number;
或者// @ts-ignore
等的确可以忽略警告,但是如果我后续把reset函数给删了,或者reset漏写了初始化代码,也没有错误提示了。
class A extends B {
index!: number; // 没有错误提示
constructor() {
super();
this.reset();
}
reset() {
// this.index = 0; // 不小心注释掉了
}
add() {
++this.index; // index为空,ts没有提示
}
}
想要排除错误的话只能把初始化写在构造函数或者定义里,
class A extends B {
index: number = 0; // 正常
constructor() {
super();
}
reset() {
this.index = 0;
}
add() {
++this.index;
}
}
我的问题是,有没有可能让ts或者ide识别出reset()函数这种情况呢?或者有没有更好的方法把重置的代码放在一个地方里,而不是写两遍初始化
一个是属性的初始化,一个是你自己写的重置函数,并不是一回事。
用
TS
了还不按照TS
的建议去写业务代码的话,上TS
的意义又在哪里?