Typescript 为什么在使用泛型类型的空类中编译不会失败?

Typescript 为什么在使用泛型类型的空类中编译不会失败?,typescript,generics,compilation,Typescript,Generics,Compilation,当我使用空类并将其调用到泛型类型类中时,编译不会失败: 您在第一个示例中声明了相同的私有属性,而不是在第二个示例中。在第二个示例中,您可以强制转换它,因为您的类形状是兼容的 例如,如果添加一个private otherColor:string=“blue”对于您的空类,它会说它们不兼容: Argument of type 'SheepV2' is not assignable to parameter of type 'BergerV2'. Property 'newColor' is m

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

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

例如,如果添加一个
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'.
您在第一个示例中声明了相同的私有属性,而不是在第二个示例中。在第二个示例中,您可以强制转换它,因为您的类形状是兼容的

例如,如果添加一个
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'.

为什么它会失败?你认为它应该失败的原因是什么?为什么失败?你认为它应该失败的错误是什么?谢谢你的回复!我想我明白了。我用“案例2”更新了操场,以进行说明。感谢您的回复!我想我明白了。我在操场上更新了“案例2”来说明。