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 anyPromise<U>whereUis any valid TypeScript type. - If
Tis not aPromise, thePromiseValue<T>type should ideally returnTitself, or a designated "fallback" type if no resolution is possible. (For this challenge, we'll aim for returningTif it's not a Promise).
Expected Behavior:
PromiseValue<Promise<string>>should resolve tostring.PromiseValue<Promise<number[]>>should resolve tonumber[].PromiseValue<Promise<boolean>>should resolve toboolean.PromiseValue<string>should resolve tostring.PromiseValue<number>should resolve tonumber.
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
PromiseValuebehave?
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.