Strojom definícia typu pre funkciu, ktorá zábaly async funkcia

0

Otázka

Mám funkcie trvá trvá svojvoľné async funkcia a vráti výsledok čaká, že async funkciu, ale zabalené v pokúste/úlovku, ktorý pridáva niektoré ďalšie logiku. Pozri ts ihrisko.

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)
);

Mám pocit, ako // @ts-expect-error v with401Redirection nemalo by byť potrebné-ako môžem odstrániť, alebo všeobecne vyčistiť písanie with401Redirection funkciu? Majte na pamäti, chcem zachovať skutočnosť, že getUser a saveItem funkcie majú svoje typy automaticky odvodiť pre mňa.

1

Najlepšiu odpoveď

2

Skúste toto:

TS Ihrisko odkaz

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;
        }
    };
}

Prečítajte si o skutočných, nadchádzajúce Awaited typ TS 4.5:

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

2021-11-13 00:21:15

V iných jazykoch

Táto stránka je v iných jazykoch

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