简体   繁体   中英

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. See code example below. Final console.log has type errors.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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