I have an interface that I want to have a method that returns an instance of the implementing class, my current implementation is this:
interface SuperClass<T extends SuperClass<any>> {
returnSelf(): T;
}
class SubClass implements SuperClass<SubClass> {
public returnSelf(): SubClass {
return this;
}
}
const subclass: SubClass = new SubClass().returnSelf();
However, this uses the any
type, which I know is supposed to be avoided at all costs. My question is, is this typesafe? I can't think of any case in which it wouldn't be, but I would like to rather use the safer unknown
type, however that doesn't compile. Why? Is there a more idiomatic way of doing this?
CodePudding user response:
You can use this
as a type.
https://www.typescriptlang.org/docs/handbook/advanced-types.html#polymorphic-this-types
interface SuperClass {
returnSelf(): this;
}
class SubClass implements SuperClass {
public returnSelf(): this {
return this;
}
}
const subclass: SubClass = new SubClass().returnSelf();
CodePudding user response:
I'm not sure if this is what you want but you can use recursive constraint:
// recursive
interface SuperClass<T extends SuperClass<T>> {
returnSelf(): T;
}
class SubClass implements SuperClass<SubClass> {
public returnSelf(): SubClass {
return this;
}
}
const subclass = new SubClass().returnSelf()