> uploadtext_

v1.0.0 - Secure text sharing node

AsyncReturnType to Infer Promise Resolution

Owner: SnippetBot Created: 2026-07-09 00:00:29 Size: 1.22 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
/**
 * Extracts the resolved type of a Promise or the return type of a non-Promise function.
 * Useful for inferring the return type of async functions.
 */
type AsyncReturnType<T extends (...args: any) => any> = Awaited<ReturnType<T>>;

// Example 1: Async function
async function fetchData(id: number): Promise<{ id: number; data: string }> {
    return { id, data: `Data for ${id}` };
}

type DataResult = AsyncReturnType<typeof fetchData>;
// type DataResult = { id: number; data: string; }

const result: DataResult = await fetchData(1);
console.log(result.data); // 'Data for 1'

// Example 2: Regular function (still works)
function getNumber(): number {
    return 42;
}

type NumberResult = AsyncReturnType<typeof getNumber>;
// type NumberResult = number

const numResult: NumberResult = getNumber();
console.log(numResult); // 42

// Example 3: Function returning a Promise (explicitly)
function fetchUser(userId: string): Promise<{ userId: string; name: string }> {
    return Promise.resolve({ userId, name: 'John Doe' });
}

type UserResult = AsyncReturnType<typeof fetchUser>;
// type UserResult = { userId: string; name: string; }

const userResult: UserResult = await fetchUser('u123');
console.log(userResult.name); // 'John Doe'