Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 防止子类中的字段重复_Typescript - Fatal编程技术网

Typescript 防止子类中的字段重复

Typescript 防止子类中的字段重复,typescript,Typescript,这就是我希望导致编译器错误的场景 编辑 这是使用babel jest运行代码时发生的场景 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 {
    // how can we decorate this field to 
    // prevent duplication in the child?
    readonly name: string; 
}

class Child extends Parent {
    readonly name: string;
}
没有这样的解决方案(也不应该?),可能是因为它与OOP原则相矛盾,比如

尽管如此,还是有一个变通办法(总是权衡取舍)

私有财产

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

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

为什么要这样做?在使用Babel编译时,我遇到了麻烦,其中子类的
name
属性未定义,即使父类已设置其值@NurbolAlpysbayev@ShaunLuttin你能举个例子吗?我可以试一试。。。我们需要一个在线的TypeScript/Babel repl.Nice概念,但是子类不是天生就修改了它们的父类吗?这有点哲学,但我想说的是,不修改父类的子类的概念是不存在的。子类的存在是对父类的修改。但是,嘿,我是来学习的。学校英语你的美语对我来说有点难,但如果我理解正确,你通常是正确的,孩子应该总是能够扩展,即修改父类属性(有意义?)的属性。然而,我不是这门课的好老师,我甚至没有CS学位。所以你应该读维基百科的文章;)我更像一个练习者哈哈好的。我的意思是我明白了我只是觉得这有点胡说八道。如果我知道胡言乱语的等价物,我会尝试在你的语言中找到:)它是俄语中的Cheh-pooh-khuh:)我必须说,在一些现实世界的案例中,许多理论原则都是胡言乱语。
class Parent {
    private name: string = '';
}