Hone logo
Hone
Problems

TypeScript Promise Type Helper

Imagine you're working with a codebase that frequently deals with asynchronous operations. You need a way to reliably extract the resolved value type from any given Promise. This is crucial for ensuring type safety when consuming asynchronous results and for building more robust and predictable asynchronous code.

Problem Description

Your task is to create a TypeScript utility type, let's call it PromiseValue<T>, that takes a type T as input and returns the type of the value that T would resolve to if T were a Promise.

Key Requirements:

  • The PromiseValue<T> type should correctly infer the resolved value type for any Promise<U> where U is any valid TypeScript type.
  • If T is not a Promise, the PromiseValue<T> type should ideally return T itself, or a designated "fallback" type if no resolution is possible. (For this challenge, we'll aim for returning T if it's not a Promise).

Expected Behavior:

  • PromiseValue<Promise<string>> should resolve to string.
  • PromiseValue<Promise<number[]>> should resolve to number[].
  • PromiseValue<Promise<boolean>> should resolve to boolean.
  • PromiseValue<string> should resolve to string.
  • PromiseValue<number> should resolve to number.

Edge Cases:

  • Consider Promise<Promise<string>>. What should this resolve to? (For this challenge, we'll assume it resolves to the inner-most resolved type, string).
  • Consider a non-promise type. How should PromiseValue behave?

Examples

Example 1:

type Example1 = PromiseValue<Promise<string>>;
// Expected: string

Example 2:

type Example2 = PromiseValue<Promise<number[]>>;
// Expected: number[]

Example 3:

type Example3 = PromiseValue<string>;
// Expected: string

Example 4: (Nested Promise)

type Example4 = PromiseValue<Promise<Promise<boolean>>>;
// Expected: boolean

Constraints

  • The solution must be implemented as a TypeScript Utility Type.
  • No runtime code is required; this is purely a type-level operation.
  • The solution should be efficient in terms of type inference time.

Notes

This challenge involves leveraging TypeScript's conditional types and infer keywords. Think about how you can inspect the structure of a type to determine if it's a Promise and, if so, extract its generic argument. You might need to use recursive conditional types to handle nested promises.

Loading editor...
typescript