abstract class Route {
abstract readonly name?: string;
protected abstract pattern: string;
public constructor() {
// Do something with `this.name` and `this.pattern`.
console.log(this.pattern); // Typecheck error
}
abstract handle(): void;
}
这会引发错误,因为this.pattern
不能在构造函数中访问。为什么我无法访问它?
(将我的评论转换为答案)
为什么我无法访问它?
因为派生类的构造函数不会被调用,所以该对象可能处于无效状态。某些语言允许来自父构造函数的虚拟调用但人们仍然普遍认为这是一种不好的做法 https://stackoverflow.com/q/962132/159145。 TypeScript 选择禁止它。
文档中提到了这一点:https://www.typescriptlang.org/docs/handbook/classes.html https://www.typescriptlang.org/docs/handbook/classes.html
[...]每个包含构造函数的派生类必须调用super()
它将执行基类的构造函数。更重要的是,在构造函数主体中访问 this 的属性之前,我们必须调用super()
。这是 TypeScript 将强制执行的一条重要规则。
万一的解决方案是通过pattern
作为参数Route
的构造函数。如果pattern
在调用父类构造函数之前无法由子类的构造函数确定,那么您需要重新考虑您的设计。
abstract class Route {
constructor(
private readonly pattern: string
)
{
console.log( pattern );
}
}
class Derived123 extends Route {
constructor() {
super( /*pattern:*/ "123" )
}
}
class Derived456 extends Route {
constructor() {
super( /*pattern:*/ "456" )
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)