typescript - 为什么在使用泛型类型的空类中编译不会失败?
解决方案
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'.
推荐阅读
- database - getLibraryDirectory 不适用于桌面应用程序
- java - java.lang.annotation 无法解析
- visual-studio-code - 从 Visual Studio Code 部署 Azure WebJob
- typescript - 禁止通过 void/never 重载来调用 0 函数
- sql - 日期范围之间的 PostgreSQL 查询,但仅在特定时间之间
- python - 如何对存储为 Python 列表中的 numpy 数组的数字运行 for 循环
- python - 用于大型处理的 Dynamodb Stream
- python - 使用 Flask 的动态表单?
- laravel - 在 Laravel Eloquent 中,我可以在没有数据透视表的情况下定义多对多关系吗?
- mysql - 为什么使用 IN 作为子查询的一部分的 where 子句在显式完成时会返回不同的行数?