Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 854
Mr. Smith Avatar asked Sep 07 '16 11:09

Mr. Smith


1 Answers

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)

like image 166
Nitzan Tomer Avatar answered Oct 10 '22 06:10

Nitzan Tomer