wea*_*nhe 7 typescript typescript-generics
为什么InstanceType
在泛型上使用是错误的?是协变的还是逆变的?
interface Ctor {
new(): Instance;
}
interface Instance {
print(): void;
}
function f1<T extends Ctor>(ctor: T) {
// Error: Type 'Instance' is not assignable to Type 'InstanceType<T>'
const ins: InstanceType<T> = new ctor();
ins.print();
}
function f2(ctor: Ctor) {
// No error
const ins: InstanceType<Ctor> = new ctor();
ins.print();
}
Run Code Online (Sandbox Code Playgroud)
Tim*_*Tim -4
因为你说 T 扩展了 Ctor,这意味着它不完全是一个 Ctor。它可能有一个返回 Instance|Instance2 的 new。Typescript 无法知道。由于 Ctor 声明它始终从其构造函数返回一个实例,因此它不知道正确派生的正确类型。
如果您希望它能够与泛型和派生类型一起使用,则需要允许它使用泛型参数推断派生类型。
interface Ctor<TInstance extends Instance> {
new(): TInstance;
}
interface Instance {
print(): void;
}
function f1<TInstance extends Instance>(ctor: Ctor<TInstance>) {
const ins: TInstance = new ctor();
ins.print();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
87 次 |
最近记录: |