Awaited Unwraps Nested Promise Types

Unwrap layered promises with the Awaited utility so ReturnType, Promise.all elements, and Promise<Promise<T>> wrappers all resolve to the final value type.

TypescriptData Fetching

Code

typescriptsnippet
26 lines
// API 层常出现多层包装:Awaited 递归解包 Promise 与 thenable,拿到最终值类型
type User = { id: number; name: string };

const loadUser = async (): Promise<User> => ({ id: 1, name: 'Ada' });

// ReturnType 给到 Promise<User>,Awaited 解开到 User
type LoadedUser = Awaited<ReturnType<typeof loadUser>>;

const cached: LoadedUser = { id: 2, name: 'Grace' };
console.log('cached user:', cached.name);

// 多层包装也会一路解到底
type Deep = Awaited<Promise<Promise<Promise<number>>>>; // number
const port: Deep = 8080;
console.log('deep unwrapped:', port);

// 泛型封装常见形态:签名标注为双层 Promise(类型层真实存在,运行时被拉平)
function layer<T>(value: T): Promise<Promise<T>> {
  return Promise.resolve(value) as unknown as Promise<Promise<T>>;
}

const wrapped = layer(cached); // 类型:Promise<Promise<User>>
wrapped.then(async (userPromise) => {
  const user: Awaited<typeof wrapped> = await userPromise;
  console.log('unwrapped as User:', user.id);
});

Output

Captured from a sandboxed run of this snippet in the build pipeline.

cached user: Grace
deep unwrapped: 8080
unwrapped as User: 2

How the snippet works

Awaited Unwraps Nested Promise Types is built around the functions loadUser and layer.

The asynchronous flow is linearized with await, keeping failure handling local.

Applying it

Entry signature: const loadUser = async ()

The demo output is labeled (cached user:, deep unwrapped:, unwrapped as User:), so each printed line can be matched to the operation producing it.

Statements that matter

wrapped.then(async (userPromise) => {
  const user: Awaited<typeof wrapped> = await userPromise;
  console.log('unwrapped as User:', user.id);
});
const loadUser = async (): Promise<User> => ({ id: 1, name: 'Ada' });
return Promise.resolve(value) as unknown as Promise<Promise<T>>;

FAQ

Are there dependencies to manage?
No. There are no dependencies to declare or install. The file defines `loadUser`, `layer` at load time.