繁体   English   中英

使用TypeScript泛型定义Factory方法的返回类型

[英]Defining return type of Factory method with TypeScript generics

本质上,我希望能够使用构造函数来调用通用TypeScript函数,并返回构造函数的乘积类型正确类型的变量。 请参见下面的代码示例。 最终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);

没有第二种类型的参数,这可能吗?

InstanceType<T>是您需要的:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM