首页 > 解决方案 > 防止子类中的字段重复

问题描述

class Parent {
    // how can we decorate this field to 
    // prevent duplication in the child?
    readonly name: string; 
}

class Child extends Parent {
    readonly name: string;
}

这就是我想导致编译器错误的场景。

编辑

这是使用 babel-jest 运行代码时出现的场景。

class Parent {
  readonly name: string; 
  constructor() { 
    this.name = 'foo';
  }
}

class Child extends Parent {
  readonly name: string;
  constructor() { 
    super();
  }
}

const child = new Child();
document.writeln(child.name); // undefined

标签: typescript

解决方案


没有这样的解决方案(不应该?),可能是因为它与 OOP 原则(如open-closed 原则)相矛盾。

不过,有一种解决方法(一如既往地进行权衡)。

将属性设为私有

class Parent {
    private name: string = '';
}

这样子类中的属性会导致编译错误“类型有单独的私有属性声明”


推荐阅读