我得到了这个错误:
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()
}
}有没有人知道为什么和如何解决这个错误?
发布于 2021-02-19 23:04:05
您是否希望存储类型为T的条目的字典?也许这就是你想要的?:
function getValue ():{[key: string]: any} {
return {key:'value'}
}
class Foo<T> {
public readonly data?: {[key: string]: T}
constructor() {
this.data = getValue()
}
}发布于 2021-02-19 23:07:30
编译器抱怨您没有在getValue函数的返回类型和data实例属性之间建立直接关系。extends子句只保证泛型类型参数至少可赋值给所提供的约束,但不会以其他方式绑定它。
此外,您的getValue函数返回一个{ key : 'value' }类型的常量。因此,当您将对getValue的调用的返回类型分配给this.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类型的值的对象。坦率地说,从您的代码片段中,根本不清楚为什么需要使类成为泛型:
class Foo {
public readonly data?: ReturnType<typeof getValue>;
constructor() {
this.data = getValue(); //OK
}
}https://stackoverflow.com/questions/66278649
复制相似问题