小编wea*_*nhe的帖子

为什么在泛型上使用 InstanceType 是错误的

为什么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)

游乐场链接

typescript typescript-generics

7
推荐指数
1
解决办法
87
查看次数

标签 统计

typescript ×1

typescript-generics ×1