[英]How to do a covariant generic return type in a method?
我有一个接口,我想要一个返回实现类实例的方法,我当前的实现是这样的:
interface SuperClass<T extends SuperClass<any>> {
returnSelf(): T;
}
class SubClass implements SuperClass<SubClass> {
public returnSelf(): SubClass {
return this;
}
}
const subclass: SubClass = new SubClass().returnSelf();
但是,这使用any
类型,我知道应该不惜一切代价避免这种类型。 我的问题是,这种类型安全吗? 我想不出任何情况下它不会,但我宁愿使用更安全的unknown
类型,但是它不能编译。 为什么? 有没有更惯用的方法来做到这一点?
您可以将this
用作类型。
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();
我不确定这是否是您想要的,但您可以使用递归约束:
// recursive
interface SuperClass<T extends SuperClass<T>> {
returnSelf(): T;
}
class SubClass implements SuperClass<SubClass> {
public returnSelf(): SubClass {
return this;
}
}
const subclass = new SubClass().returnSelf()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.