【问题标题】:Type 'XX' is not assignable to type 'YY'. 'XX' is assignable to the constraint of type 'YY', but 'YY' could be instantiated类型“XX”不可分配给类型“YY”。 'XX' 可分配给'YY' 类型的约束,但'YY' 可以被实例化
【发布时间】:2021-05-22 12:11:58
【问题描述】:

我收到了这个错误:

Type '{ [key: string]: any; }' is not assignable to type 'T'.
  '{ [key: string]: any; }' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{ [key: string]: any; }'.(2322)

来自这段代码:

function getValue ():{[key: string]: any}  {
    return {key:'value'}
}

class Foo<T extends {[key: string]: any}> {
    public readonly data?: T

    constructor() {
        this.data = getValue()
    }
}

有谁知道为什么以及如何解决这个错误?

【问题讨论】:

标签: typescript typescript-generics typescript-class


【解决方案1】:

编译器抱怨您没有在getValue 函数的返回类型和data 实例属性之间建立直接关系。 extends 子句仅保证至少泛型类型参数可分配给提供的约束,但不以其他方式绑定它。

此外,您的getValue 函数返回{ key : 'value' } 类型的常量。因此,当您将调用的返回类型分配给getValuethis.data 时,编译器会查看后者是否是前者的超类型,并看到您只保证data{ [key: string]: any },或者,在简单的英语:

“具有任意数量的字符串类型键和任意类型值的某种对象”

很明显data 可以{ key : 'value' } 类型没有任何共同之处。现在,看看如果你明确告诉编译器 T 应该符合 getValue 的返回类型会发生什么:

class Foo<T extends {[key: string]: any}> {
    public readonly data?: T | ReturnType<typeof getValue>;

    constructor() {
        this.data = getValue(); //OK
    }
}

现在编译器很高兴,因为它可以建立关系,但是您将被限制为具有单个键 key 和类型为 string 的值的对象。坦率地说,从您的 sn-p 来看,您根本不清楚为什么需要将类设为通用:

class Foo {
    public readonly data?: ReturnType<typeof getValue>;

    constructor() {
        this.data = getValue(); //OK
    }
}

【讨论】:

    【解决方案2】:

    您是否要存储类型为 T 的项目字典?那么也许这就是你想要的?:

    function getValue ():{[key: string]: any}  {
        return {key:'value'}
    }
    
    class Foo<T> {
        public readonly data?: {[key: string]: T}
    
        constructor() {
            this.data = getValue()
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-02-13
      • 2020-11-25
      • 2019-12-13
      • 2021-10-14
      • 2020-08-17
      • 1970-01-01
      • 2021-12-10
      • 1970-01-01
      • 2021-06-19
      相关资源
      最近更新 更多