类型“XX”不能分配给类型“YY” 'XX' 可分配给类型为 'YY' 的约束,但可以实例化 'YY'

问题描述

我收到此错误

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()
    }
}

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

解决方法

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

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

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

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

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

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

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

很明显,{ [key: string]: any } candata 类型没有任何共同之处。现在,看看如果你明确告诉编译器 { 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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...