Search code examples
typescripttyping

Typescript method which always returns own type / "type X not assignable to type this"


I'm trying to write a method which always returns the type it's called on. I've found the "this" type which allows something similar, but it appears that it is only compatible with the literal "this", and not with other instances of the same class.

abstract class A {
    // I need a method which always returns the same type for a transformation method,
    // a clone function would need the same interface
    abstract alwaysReturnSameType(): this
}
class B extends A {
    x:number
    constructor(x:number) {
        this.x = x
    }
    alwaysReturnSameType():this {
        return new B(this.x + 1) // ERROR: Type 'B' is not assignable to type 'this'.
        // this works, but isn't what I need: return this
    }
}

I've looked at some very long issues on github (e.g. https://github.com/Microsoft/TypeScript/issues/5863) but I'm not sure if there's a solution to be found there.

Is there a way of solving this or should I just cast to supress the error, i.e. return <this> new B()


Solution

  • You can cast it to this:

    class B extends A {
        x: number;
    
        constructor(x: number) {
            super();
            this.x = x
        }
    
        alwaysReturnSameType(): this {
            return new B(this.x + 1) as this;
        }
    }
    

    (code in playground)

    I'm not sure why it doesn't work without it.


    It actually makes sense that it complains about returning a new B.
    When you declare that you return this it means "the current instance", but a new instance is different.