我预计以下打字稿代码可能会导致编译错误,因为派生类中的属性与基类中的属性具有相同的名称,但类型不同。但是,此代码编译时不会出现问题,并且Derived.property遮盖了Base.property,从而导致了细微的错误。是否可以通过编译器或linter阻止此类代码?
class Base {
protected property: {};
constructor(property: {}) {
this.property = property;
}
}
class Derived extends Base {
property = 1;
}
实际上,这是在设置空对象={}
时所期望的。因为它可以扩展为数字,字符串等。
您真正想要的是限制其类型
type Options = {
option1?: boolean
}
class Base {
protected property: Options;
constructor(property: {}) {
this.property = property;
}
}
class Derived extends Base {
property = 1; // does not work (2416)
}