简体   繁体   English

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

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

Essentially I want to be able to call a generic TypeScript function with a constructor function and return a correctly typed variable of the type of the product of the constructor function. 本质上,我希望能够使用构造函数来调用通用TypeScript函数,并返回构造函数的乘积类型正确类型的变量。 See code example below. 请参见下面的代码示例。 Final console.log has type errors. 最终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}`);

I've searched other answers and nothing seems to quite cover this. 我搜索了其他答案,似乎没有什么能掩盖这一点。 I also feel like this might be impossible as I'm trying to extract the type generically and not from an instance. 我也觉得这可能是不可能的,因为我试图从类型而不是从实例中提取类型。

At simplest I want this function to work, with correct typing: 最简单地说,我希望此功能可以正确键入以下内容:

let val: SomeType = retrieve(SomeTypeConstructor);

Is this possible, without a second type parameter? 没有第二种类型的参数,这可能吗?

InstanceType<T> is what you need: 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