【问题标题】:A generic interface with type constraints accepting a default type具有接受默认类型的类型约束的通用接口
【发布时间】: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


    【解决方案1】:

    看起来当 TypeScript 在 T 为默认值时检查约束是否满足时,它不够聪明,无法将约束中出现的 T 替换为默认值。 IMO,将其作为问题提交并让 TypeScript 团队决定如何处理是合理的;我搜索并没有发现截至 2018-07-28 存在的问题。

    这是我能找到的最佳解决方法:

    interface Options<T extends DateAdapter<T> = StandardDateAdapter & DateAdapter<T>> {
      until?: T;
    }
    

    那么默认值实际上是StandardDateAdapter &amp; DateAdapter&lt;{}&gt;,它看起来很难看,但可以分配给StandardDateAdapter,因此希望它能满足您的所有需求。

    【讨论】:

    • 谢谢!我打算等几天让其他人有机会回复,但是,假设其他人不知道更好的解决方案,我会将其标记为正确。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多