Conditional Types With Infer Extraction

Extract element, return, and promise types with conditional types and infer so utility types read the shape instead of duplicating it.

TypescriptData Integrity

Code

typescriptsnippet
22 lines
type ElementType<T> = T extends readonly (infer E)[] ? E : never;
type ReturnTypeOf<T> = T extends (...args: never[]) => infer R ? R : never;
type Unwrapped<T> = T extends Promise<infer V> ? Unwrapped<V> : T;

// 递归解包嵌套 Promise
type Nested = Promise<Promise<string[]>>;

async function loadUsers(): Promise<{ id: number; name: string }[]> {
  return [{ id: 1, name: 'alice' }];
}

type User = ElementType<ReturnTypeOf<typeof loadUsers>>;

declare const user: User;
console.log(user.id, user.name);

// Unwrapped<Nested> = string[]
const unwrapped: Unwrapped<Nested> = ['plain'];
console.log(unwrapped.length);

// 组合:从 async 函数直接推导"已解包数据"类型
type LoadedData = Unwrapped<ReturnTypeOf<typeof loadUsers>>;

How it works

Conditional Types With Infer Extraction is built around the function loadUsers.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

What comes back is a new object, not a reference to anything passed in.

Applying it

The primary signature is async function loadUsers()

Statements that matter

type ReturnTypeOf<T> = T extends (...args: never[]) => infer R ? R : never;
type Unwrapped<T> = T extends Promise<infer V> ? Unwrapped<V> : T;
async function loadUsers(): Promise<{ id: number; name: string }[]> {
return [{ id: 1, name: 'alice' }];
}

Interactive Tools for This Topic

FAQ

Does `loadUsers` modify its input?
No. Nothing passed in is written to, which makes the call safe on shared data.
What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. The file defines `loadUsers` at load time.