首页 > 解决方案 > 为什么在使用泛型类型的空类中编译不会失败?

问题描述

当我使用空类并将其调用为泛型类型类时,编译不会失败:

查看游乐场

标签: typescriptgenericscompilation

解决方案


Argument of type 'SheepV1' is not assignable to parameter of type 'BergerV1'.
  Types have separate declarations of a private property 'color'.`

您在第一个示例中声明了相同的私有财产,而不是在第二个示例中。在您的第二个示例中,您可以转换它,因为您的类形状是兼容的。

例如,如果您将 a 添加private otherColor: string = "blue";到您的空类,它会说它们不兼容:

Argument of type 'SheepV2' is not assignable to parameter of type 'BergerV2'.
  Property 'newColor' is missing in type 'SheepV2' but required in type 'BergerV2'.

这两个本质上是相同的问题,除了第一个是因为它声明了相同的属性。第二个是因为它们不兼容。


编辑:要扩展并获得更清晰的错误,如果您尝试使用空类设置:

const test1: BergerV1 = new SheepV1() as BergerV1;
const test2: BergerV2 = new SheepV2() as BergerV2;

V1 会出现此错误,V2 不会出现此错误:

Conversion of type 'SheepV1' to type 'BergerV1' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
  Types have separate declarations of a private property 'color'.

推荐阅读