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?
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();
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.