【发布时间】:2018-07-29 03:29:26
【问题描述】:
我在 typescript 中创建了一个简单的通用接口
interface DateAdapter<T> {
clone(): T;
}
我有一个实现上述接口的简单类
class StandardDateAdapter implements DateAdapter<StandardDateAdapter> {
clone: () => StandardDateAdapter;
}
然后我有一个通用的Options 接口,它接受扩展DateAdapter 的类型。默认情况下,我希望类型参数为 StandardDateAdapter,所以我将其设置为:
interface Options<T extends DateAdapter<T> = StandardDateAdapter> {
until?: T;
}
不幸的是,typescript 不喜欢这样并抛出错误
Type 'StandardDateAdapter' does not satisfy the constraint 'DateAdapter<T>'.
Types of property 'clone' are incompatible.
Type '() => StandardDateAdapter' is not assignable to type '() => T'.
Type 'StandardDateAdapter' is not assignable to type 'T'.
有什么想法可以解决这个问题吗?这是一个错误吗?谢谢!
注意:DateAdapter 只是通用的,因为我希望clone() 的返回类型等于实现DateAdapter 的类的类型。我最初在 DateAdapter 中尝试了clone(): this;,但打字稿足够聪明,可以意识到 StandardDateAdapter#clone() 返回 new StandardDateAdapter !== this
【问题讨论】:
标签: typescript generics