首页 > 解决方案 > 当类型“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

然后我没有错误。

我真的很困惑。

打字稿游乐场

标签: typescript

解决方案


推荐阅读