简体   繁体   English

将只读变量传递给父构造函数 | 打字稿

[英]Passing a readonly variable to parent constructor | Typescript

I'm new to TypeScript and I'm trying to pass a readonly variable to the constructor of a parent class:我是 TypeScript 的新手,我正在尝试将readonly变量传递给父类的构造函数:

abstract class ChildClass extends ParentClass {
    private readonly READ_ONLY: number= 1;

    public constructor(foo: string)
        // 'super' must be called before accessing 'this' in the constructor of a derived class. ts(17009)
        super(foo, this.READ_ONLY); 
    }
}

ChildClass will be extended by more classes, therefore the abstract. ChildClass 将被更多的类扩展,因此是抽象的。

Is there any way I can pass the read-only variable in the super constructor?有什么办法可以在super构造函数中传递只读变量吗?

This has nothing to do with readonly .这与readonly无关。

You cannot reference any property of this before the superclass's constructor is called.在调用超类的构造函数之前,您不能引用this的任何属性。 So you have to do this in a different way.所以你必须以不同的方式做到这一点。

Perhaps READ_ONLY is a protected property of ParentClass , and then child classes can set a new value for it.也许READ_ONLYParentClass的受保护属性,然后子类可以为其设置新值。

class ParentClass {
  protected readonly READ_ONLY: number = 1;
  constructor(foo: string) {
    console.log('used READ_ONLY: ', this.READ_ONLY)
  }
}

class ChildClass extends ParentClass {
  protected readonly READ_ONLY: number = 2;
}

new ParentClass('foo') // used READ_ONLY: 1
new ChildClass('foo') // used READ_ONLY: 2

This works because protected just means private to the outside, but public to subclasses.这是可行的,因为protected仅意味着对外部private ,但对子类public

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM