Optional readonly property or getter in abstract class

1.2k views Asked by At

This code was valid for typescript 3, but in typescript 4 it produces an error

'smth' is defined as a property in class 'A', but is overridden here in 'C' as an accessor.

Yes, it is listed in breaking changes, but here is a bit specific case. Base class A declares an optional readonly property and never create it. It's logical, that it should not care about the way how it is implemented in child class.

Playground

abstract class A {
    protected readonly smth?: number

    public f() {
        console.log(this.smth)
    }
}

class B extends A {
    smth = 10
}

class C extends A {
    get smth() { return Math.random() }
}

class D extends A {
}

new B().f()
new C().f()
new D().f()

I was thinking about marking property as abstract in class A - it solves problem with different overrides in B and C but introduces error in D:

Non-abstract class 'D' does not implement inherited abstract member 'smth' from class 'A'.

As the property is optional, I don't want to require child classes to implement it and I want any implementation (with property or with getter) to be valid.

So what can I change in class A so that all 3 classes (B, C and D) will be valid?

Number of such child classes in my project is

B - 16
C -  2
D - 90

so I definitely don't want to change D, also I can't change C to B as they are calculating dynamic value. Changing to getter as to the most rare variant seem not very logical too, but at last has some sense. But currently I've marked property in C-classes by @ts-ignore.

0

There are 0 answers