【发布时间】: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()
}
}
有谁知道为什么以及如何解决这个错误?
【问题讨论】:
-
TLDR:如果您将
interface A { key: { sub: number } }作为类型参数传递,您认为编译器应该怎么做?这正是它告诉您的内容:getValue的返回类型可能与data的预期不同,因为T和ReturnType<typeof getValue>之间没有直接关系。
标签: typescript typescript-generics typescript-class