尝试覆盖具有通用返回类型的子类中的方法,并出现此错误。我一直在阅读could be instantiated with a different subtype of constraint 'object',但无法解决自己的情况。有什么建议吗?
Type '{ deployments: { [deploymentId: string]: string[]; }; }' is not assignable to type 'SomeInterface'.
'{ deployments: { [deploymentId: string]: string[]; }; }' is assignable to the constraint of type 'SomeInterface', but 'SomeInterface' could be instantiated with a different subtype of constraint '{}'.(2322)
class SomeClass {
testGenericMethod<T>(): T {
throw new Error('Implement this.')
}
}
interface SomeInterface {
deployments: { [deploymentId: string]: Array<string> }
}
class ImplementSomeClass extends SomeClass {
testGenericMethod<SomeInterface>(): SomeInterface {
const deployments: { [deploymentId: string]: Array<string> } = {}
return { deployments }
}
}
答案 0 :(得分:0)
您使用的是泛型变量<SomeInterface>
,它将覆盖函数范围内的接口定义。
使用另一个通用变量。例如,如果仍然需要是SomeInterface
:
class ImplementSomeCLass {
testGenericMethod<T extends SomeInterface>(): SomeInterface {
const deployments: { [deploymentId: string]: Array<string> } = {}
return { deployments }
}
}
请记住,在函数定义中,泛型是变量。您可以为其指定默认值
testGenericMethod<T = SomeInterface>(): SomeInterface {/** **/}
或者您可以将它们限制为某些类型:
testGenericMethod<T extends SomeInterface>() : SomeInterface {/** **/}
在前一种情况下,您可以使用任何类型调用函数:
const myInterface = testGenericMethod<any>();
在后一种情况下,可以使用满足约束的任何类型:
const myInterface = testGenericMethod<SomeInterface & MyOtherInterface>();