타이프 라이터 유형에 대한 정의 기능을 감싸주는 비동기 기능

0

질문

내가 함수는 임의의 비동기 기능의 결과를 반환합니다 기다리는 비동기 기능이 있고,포장에서 시도/을 잡을 추가하는 몇 가지 추가 논리입니다. 보 ts playground.

const with401Redirection =
    <T extends (...args: any[]) => Promise<any>>(
        call: T
    ): ((...args: Parameters<T>) => ReturnType<T>) =>
    // @ts-expect-error
    async (...args: Parameters<T>): ReturnType<T> => {
        try {
            return await call(...args);
        } catch (error) {
            if ((error as any).httpStatus === 401) {
                // do some stuff here
            }

            throw error;
        }
    };

interface User {
    id: string;
    name: string;
}

interface ItemPayload {
    field1: string;
    field2: string;
}

interface ItemResponse {
    id: string;
    field1: string;
    field2: string;
}

const client = {
    get<ResponseType>(url: string): Promise<ResponseType> {
        // logic to hit server and return result here
        return '' as any;
    },
    post<ResponseType>(url: string, body: Record<string, any>): Promise<ResponseType> {
        // logic to hit server and return result here
        return '' as any;
    }
};

const getUser = with401Redirection(() =>
    client.get<User>('url_1')
);

const saveItem = with401Redirection((body: ItemPayload) =>
    client.post<ItemResponse>('url_2', body)
);

같은 느낌 // @ts-expect-errorwith401Redirection 필요는 없--어떻게 이를 제거할 수 있습니는 일반적으로 정의 입력 with401Redirection 기능입니까? 염두에 두고 싶어지는 사실에 getUsersaveItem 기능 있는 자신의 유형이 자동으로 유추한다.

1

최고의 응답

2

이것을 보십시오:

TS 놀이터 링크

type Awaited<T> = T extends PromiseLike<infer U> ? Awaited<U> : T;
type AsyncFn = (...args: any[]) => Promise<any>;

function with401Redirection <T extends AsyncFn>(call: T): (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>> {
    return async (...args: Parameters<T>) => {
        try {
            return await call(...args);
        }
        catch (exception) {
            if (typeof exception === 'object' && (exception as any)?.httpStatus === 401) {
                // do some stuff here
            }
            throw exception;
        }
    };
}

읽기에 대해 실제,향후 Awaited 입력 TS4.5:

https://devblogs.microsoft.com/typescript/announcing-typescript-4-5-beta/#the-awaited-type-and-promise-improvements

2021-11-13 00:21:15

다른 언어로

이 페이지는 다른 언어로되어 있습니다

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................