2

I was using ReturnType<typeof function-name> to extract the return type - very useful.

It now happens that the return type of the function is a Promise, and I want to further extract the type parameter, example:

const someFunction = (): Promise<MysteryType> => { ... some code ... }

type TheReturnType = ReturnType<typeof someFunction>

type ExtractTypeFromPromise = UNKNOWN<TheReturnType>

Is this currently possible?

Arie Milner
  • 316
  • 2
  • 10
  • Does this answer your question? [TypeScript: how to extract the generic parameter from a type?](https://stackoverflow.com/questions/44851268/typescript-how-to-extract-the-generic-parameter-from-a-type) – kaya3 Mar 26 '22 at 20:13

1 Answers1

4

The TypeScript docs have a section called "Type inference in conditional types" that gives a nice answer with the Unpacked<T> type definition:

type Unpacked<T> =
    T extends (infer U)[] ? U :
    T extends (...args: any[]) => infer U ? U :
    T extends Promise<infer U> ? U :
    T;

Along with some examples of the results:

type T0 = Unpacked<string>;  // string
type T1 = Unpacked<string[]>;  // string
type T3 = Unpacked<Promise<string>>;  // string

I wasn't familiar with inferred types, so thanks for helping me learn something new! :)


Update addressing additional question:

Is there a way to do this where you force the type at compile time to be of that instance.
Example: type T0 = UnpackedArray<string> // fail because it's not an Array

Yes! It's possible to place constraints on the generic type using extends:

type UnpackedArray<T extends Array<any>> =
    T extends (infer U)[] ? U : never;

type T2 = UnpackedArray<string[]>; // string
type T3 = UnpackedArray<string>;   // Error: Type 'string' does not satisfy the constraint 'any[]'.
Sly_cardinal
  • 12,270
  • 5
  • 49
  • 50
  • Follow up question, is there a way to do this where you force the type at compile time to be of that instance. Example: `type T0 = UnpackedArray // fail because it's not an Array` – Arie Milner Jul 03 '19 at 22:02
  • @ArieMilner Yes, see my updated answer on how to constrain the type at compile time :) – Sly_cardinal Jul 04 '19 at 00:45