0

I have a code

class Base {
    static text: string;

    static set(text: string) {
        const self = class extends this {};
        self.text = text;
        return self
    }
}


class ChildBase extends Base {
    static print(moreText: string) {
        return moreText + this.text;
    }
}


ChildBase.set('good').print('prefix')
                      // Error TS2339: Property 'print' does not exist on type 'typeof self'. 

How to call print after the call set static method. I need clone class before calling another static method in ChildBase

bt ra
  • 17
  • 6
  • Why mark as `static` the `print` method? The `set` returns an instance. – Mario Vernari Dec 31 '21 at 09:28
  • @MarioVernari I mark `print` as `static` because I need call `static text` – bt ra Dec 31 '21 at 09:32
  • Be careful: the `this` is not what you think. You're inside a `static` function and `this` is depending on the caller. Read here: https://stackoverflow.com/questions/50285240/es6-this-within-static-method – Mario Vernari Dec 31 '21 at 09:35
  • @MarioVernari I know it, when call `ChildBase.set('good')` it means `this` is `ChildBase`. It works correctly if I use javascript, but it's fail in typescript – bt ra Dec 31 '21 at 09:39
  • Typescript fails the compilation, because it is not able to resolve the `print` method. However, it seems to me an anti-pattern. Why don't you enclose the `set` functionality in the `print` method? – Mario Vernari Dec 31 '21 at 09:53
  • I have many `static` method in `ChildBase` so that reason I avoid embedding `set` inside – bt ra Dec 31 '21 at 10:25

0 Answers0