typescript - 当类型“any”与其他类型不兼容时
问题描述
我不明白为什么这两种静态方法彼此不兼容。据我了解,类型any
与任何东西都兼容。考虑这个例子。
class A {
static createInstance<T=any>(data:T):A {
return new A()
}
}
class B extends A{
constructor(public role: string = 'manager') {
super()
}
static createInstance<T extends { role: string }>(data:T): B{
return new B(data.role)
}
}
我收到此错误:
Class static side 'typeof B' incorrectly extends base class static side 'typeof A'.
Types of property 'createInstance' are incompatible.
Type '<T extends { role: string; }>(data: T) => B' is not assignable to type '<T = any>(data: T) => A'.
Types of parameters 'data' and 'data' are incompatible.
Type 'T' is not assignable to type '{ role: string; }'.
我的想法是,如果我any
在父类 ( A
) 中使用 as 类型,我可以在子类 ( ) 中做任何我喜欢的事情B
。所以我不确定发生了什么。另外,如果我将createInstance
类中的方法签名更改A
为:
createInstance(data:any):A
然后我没有错误。
我真的很困惑。
解决方案
推荐阅读
- r - 标准化 R 中数据集之间的时间数据
- swift - 在 Xcode 中创建 UIButton,右侧为图标,左侧为文本
- java - 从 Maven、Tomcat、jax-rs、Jersey 项目中分离前端代码
- amazon-web-services - AWS Cognito 中的自定义电话验证?
- c++ - 找到循环系统中两个值之间差异的最佳方法?
- python - scrapy splash应用程序中的长链异常
- javascript - 使用 javascript 在 json 中组合对象
- c# - C#打开PPTX文件到特定幻灯片索引
- django - 如何在具有字段作为外键的 django 模型中查询?
- angular - Angular/Typescript - 布尔变量未在 .subscribe 上更新