Mr. Smith Mr. Smith - 3 months ago 10
TypeScript Question

Typescript: Return "this" from generic base class


I want to return "this" from the base class as the generics type parameter.

class ExampleClass<T> {
public returnThis = (): T => {
return <T>this;
}
}


I know that i cannot cast to T because typescript doesn't know that T derives from ExampleClass.

But is there a way to do this?

Answer

You can just return type this:

class ExampleClass<T> {
    public returnThis = (): this => {
        return this;
    }
}

It's covered in the Polymorphic this types section of the docs.


Edit

No, it will return the type of the actual instance, for example:

class BaseClass {
    public returnThis(): this {
        return this;
    }
}

class ExampleClass extends BaseClass {}

let base = new BaseClass();
let base2 = base.returnThis(); // base2 instanceof BaseClass

let example = new ExampleClass();
let example2 = example.returnThis(); // example2 instanceof ExampleClass 

(code in playground)