工厂方法与打字稿泛型定义返回类型

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

基本上我希望能够调用同一个构造函数创建一个通用的打字稿功能和返回的构造函数的产品的类型的正确类型的变量。请参见下面的代码示例。最终的console.log具有类型的错误。

class TestType {
  constructor(
    public someVal: number
  ) {}
}

type GenericConstructor = new (...args: any) => any;

let map = new Map<GenericConstructor, any>();
map.set(TestType, new TestType(7));

console.log(map.get(TestType).someVal);

function retrieve<T extends GenericConstructor>(constructor: T): T {
  return map.get(constructor);
}

let retrieved = retrieve(TestType);
console.log(`retrieved: ${retrieved.someVal}`);

我搜索其他答案,似乎没有什么能盖住这个。我也觉得,因为我试图从一个实例一般不提取的类型,这可能是不可能的。

在最简单的我想此功能工作,以正确的打字:

let val: SomeType = retrieve(SomeTypeConstructor);

这是可能的,没有第二个类型参数?

javascript typescript
1个回答
1
投票

InstanceType<T>是你所需要的:

function retrieve<T extends GenericConstructor>(constructor: T): InstanceType<T> {
  return map.get(constructor);
}
© www.soinside.com 2019 - 2024. All rights reserved.