【发布时间】:2021-03-09 20:57:54
【问题描述】:
我对这些课程有疑问。我想使用doSomething() 类B 独有的方法而不每次都进行类型转换,但是当我将属性a 指定为B 类型时,它告诉我它没有在构造函数中分配,这有点错误,因为父构造函数进行了赋值。
class A {
}
class B extends A {
doSomething() { }
}
class One {
constructor(protected a: A){ }
}
class Two extends One {
protected a: B // Property 'a' has no initializer and is not definitely assigned in the constructor.
constructor(){
super(new B());
// If I enter "this.a = new B();" here then the error disappears, but the code is redundant.
}
doStuff() {
this.a.doSomething()
}
}
我做错了什么?
【问题讨论】:
-
您说父类构造函数进行赋值,但在您提供的代码中,父类构造函数中没有发生赋值。哪一个是真的?附:请不要添加不相关的标签。
-
在打字稿中,constructor(protected a: A){ } 是 constructor (a: A) { this.a = a; 的简写。 }
-
是的,但是你为什么期望它在严格模式下不会出错(我知道发出的代码是
constructor(a) { this.a = a; })呢?除了 jcalz 的回答之外,您还可以使用 definite assignment assertions,这似乎是一个 good case。
标签: typescript typescript-class