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?
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With