0

我收到了这个错误:

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

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

4

2 回答 2

0

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

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

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

    constructor() {
        this.data = getValue()
    }
}
于 2021-02-19T15:04:05.483 回答
0

编译器抱怨您没有在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
    }
}

现在编译器很高兴,因为它可以建立关系,但是您将被限制为具有单个 keykey和 type 值的对象string。坦率地说,从您的代码片段中,您根本不清楚为什么需要使该类成为通用类:

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

    constructor() {
        this.data = getValue(); //OK
    }
}
于 2021-02-19T15:07:30.197 回答