【问题标题】:TypeScript Generic type intersection does not satisfy itselfTypeScript 泛型类型交集不满足自身
【发布时间】:2021-07-01 03:04:28
【问题描述】:

我对泛型类型有疑问。它的简化版是这样的。

import { Document, Model } from 'mongoose';

interface Base {
  age: number;
}

class Test<T extends Base> {
  private t: Model<T & Document>
}

这部分 Model&lt;T &amp; Document&gt; 出现错误,上面写着:

Type 'T & Document<any, {}>' does not satisfy the constraint 'Document<any, {}>'

有人知道吗?

【问题讨论】:

    标签: typescript mongoose typescript-typings typescript-generics


    【解决方案1】:

    那是因为Document的类型是class Document<...>,所以你不能直接使用intersecion type&amp;和“Object”类型。 p>

    要解决这个问题,您可以使用extends 来扩展类,如下所示:

    class Base extends Document {
      age?: number;
    }
    
    class Test<T extends Base> {
      private t?: Model<T>;
    }
    

    【讨论】:

    • 非常正确!无论我搜索多少,我都没有看到你说的。它让我重构了我的一些代码,但现在它更有意义了。谢谢
    猜你喜欢
    • 2021-10-18
    • 1970-01-01
    • 2020-07-31
    • 1970-01-01
    • 2020-10-25
    • 2019-02-10
    • 2020-07-07
    • 2019-05-30
    • 1970-01-01
    相关资源
    最近更新 更多