Promise Type Helper in TypeScript
Creating utility types in TypeScript can significantly improve code readability and maintainability. This challenge asks you to build a type helper that extracts the resolved value type from a Promise<T> type. This is useful when you need to work with the type of data that a promise will eventually resolve to, without having to manually extract it.
Problem Description
You need to create a TypeScript type called ResolvedType<T> that takes a Promise<T> as input and returns the type T. In essence, it strips away the Promise wrapper and exposes the underlying type that the promise resolves to. This is particularly helpful when dealing with asynchronous operations and wanting to ensure type safety when accessing the resolved data.
Key Requirements:
- The type
ResolvedType<T>must accept aPromise<T>as input. - It must return the type
T. - The type should work correctly for any valid TypeScript type
T. - The type should be a conditional type.
Expected Behavior:
ResolvedType<Promise<string>>should evaluate tostring.ResolvedType<Promise<number>>should evaluate tonumber.ResolvedType<Promise<{ name: string, age: number }>>should evaluate to{ name: string, age: number }.ResolvedType<Promise<Promise<boolean>>>should evaluate toPromise<boolean>. (This demonstrates handling nested promises - the helper should still extract the inner resolved type).
Edge Cases to Consider:
Promise<void>: Should resolve tovoid.Promise<null>: Should resolve tonull.Promise<undefined>: Should resolve toundefined.- Nested Promises: The helper should extract the type of the innermost resolved promise.
Examples
Example 1:
Input: Promise<string>
Output: string
Explanation: The ResolvedType helper extracts the 'string' type from the Promise<string>.
Example 2:
Input: Promise<Promise<number>>
Output: number
Explanation: The ResolvedType helper extracts the 'number' type from the nested Promise<Promise<number>>.
Example 3:
Input: Promise<void>
Output: void
Explanation: The ResolvedType helper correctly handles the 'void' type.
Constraints
- The solution must be a valid TypeScript type definition.
- The solution should be concise and readable.
- The solution should not use any external libraries.
- The solution must work with all valid TypeScript types for
T.
Notes
Consider using conditional types to achieve this. Think about how to check if a type is a Promise and then extract the type parameter if it is. The typeof operator and conditional type inference can be helpful here. Remember that TypeScript's type system is powerful, and you can leverage it to create elegant and reusable type helpers.