简体   繁体   中英

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:

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.

Is there any way I can pass the read-only variable in the super constructor?

This has nothing to do with readonly .

You cannot reference any property of this before the superclass's constructor is called. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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