Home > Net >  Bind class instance property to class extended type chain. Tell TS to allow JS "this" beha
Bind class instance property to class extended type chain. Tell TS to allow JS "this" beha

Time:11-06

For this snippet:

class Parent {
    constructor() {
        
    }
    // this method is called from child, 
    // so 'this' is type of Child and cosmisFunc exists
    callChildFunction() {
        this.cosmisFunc() // compiler error here: Property 'cosmicFunc' does not exist on type 'Child'.ts(2339)
    }
}

class Child extends Parent {
    constructor() {
        super();
    }

    someMethod() {
        this.callChildFunction()
    }

    cosmisFunc() {
        console.log('oh mama')
    }
}

//not meaningfull code... instance construction...
myChildInstance.someMethod()

I'd like to tell typescript that method will be called from child class in parent class to that this error ts(2339) is not thrown. Apparently typescript prevents you from calling callChildFunction with a different this which is allowed by JS. I was thinking there could/should be a way in typescript to tell the compiler that this will always by whithin the hierarchy propotipal chain (meaning that this will alway refer to a Parent or a Child instance).

Playground

CodePudding user response:

You should just have the method on the parent and if it's called it should throw (to mimic the original behavior that when you call it, an error will be thrown):

class Parent {
    constructor() {
        
    }
    callChildFunction() {
        this.cosmisFunc()
    }
    cosmisFunc() {
        throw new Error("cannot call cosmisFunc on Parent");
    }
}

Then TS is happy since this will always have a cosmisFunc.

Playground

  • Related