typescript - 防止子类中的字段重复
问题描述
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
解决方案
没有这样的解决方案(不应该?),可能是因为它与 OOP 原则(如open-closed 原则)相矛盾。
不过,有一种解决方法(一如既往地进行权衡)。
将属性设为私有
class Parent {
private name: string = '';
}
这样子类中的属性会导致编译错误“类型有单独的私有属性声明”
推荐阅读
- node.js - MongoDB/Mongoose:根据给定文档中的值进行搜索,而不首先返回该文档
- android - 二进制 XML 文件第 9 行:夸大类活动时出错
- php - 扩展 PHP 类以允许通过 __callStatic 找到新方法
- visual-studio-2019 - 我如何将两个表格堆叠在一起
- javascript - React-Redux,如何在渲染新组件之前设置全局状态?
- typescript - 试图为 TypeScript EventListeners 建立一个泛型类型并得到一个奇怪的错误
- flutter - 为什么我不能在颤振中访问 Firestore 值?
- r - 将大型 zip tsv 文件导入 R 时出现内存问题
- reactjs - Redirect from 在反应路由器中意味着什么
- c# - 为什么我不能使用他们提供的示例通过 mapbox api 创建一个有效的样式?