如何使TypeScript推断动态new()调用的类型

问题描述 投票:1回答:1

我正在动态创建子类,我希望工厂函数知道子类的返回类型。

我可以进行强制转换,但是我想知道是否存在一种无需强制转换就可以推断出它的方法。

class Hello { 
  a = 1;
}

class Hello2 extends Hello{ 
  b = 2; 
}

class Hello3 extends Hello { 
  c = 3; 
}

function create<T extends typeof Hello>(ctor: T): InstanceType<T> {
  // If I don't cast this, it won't compile
  return new ctor() as InstanceType<T>;
}

// Fails as it should because it's not a constructor of the right type
const h1 = create(Number);
const h2 = create(Hello2); 
console.log(h2.b); // no error
const h3 = create(Hello3);
console.log(h3.c); // no error
typescript type-inference
1个回答
1
投票

,如果您改为使类实例通用(不是静态端/构造函数)?应该可以为您解决,例如here

© www.soinside.com 2019 - 2024. All rights reserved.