【问题标题】:How to prevent derived class properties from shadowing base class properties如何防止派生类属性遮蔽基类属性
【发布时间】:2019-11-11 04:49:07
【问题描述】:

我预计以下打字稿代码可能会导致编译错误,因为派生类中的属性与基类中的属性名称相同,但类型不同。但是,此代码编译时没有问题,并且 Derived.property 会影响 Base.property,从而导致细微的错误。是否可以通过编译器或 linter 来防止这种代码?

class Base {
  protected property: {};
  constructor(property: {}) {
    this.property = property;
  }
}

class Derived extends Base {
  property = 1;
}

【问题讨论】:

  • 这个相关的answer 可能也很有趣。

标签: typescript


【解决方案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)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    • 2015-04-09
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    相关资源
    最近更新 更多