繁体   English   中英

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

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

我是 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 将被更多的类扩展,因此是抽象的。

有什么办法可以在super构造函数中传递只读变量吗?

这与readonly无关。

在调用超类的构造函数之前,您不能引用this的任何属性。 所以你必须以不同的方式做到这一点。

也许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

这是可行的,因为protected仅意味着对外部private ,但对子类public

暂无
暂无

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

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