내가 함수는 임의의 비동기 기능의 결과를 반환합니다 기다리는 비동기 기능이 있고,포장에서 시도/을 잡을 추가하는 몇 가지 추가 논리입니다. 보 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-error
에 with401Redirection
필요는 없--어떻게 이를 제거할 수 있습니는 일반적으로 정의 입력 with401Redirection
기능입니까? 염두에 두고 싶어지는 사실에 getUser
고 saveItem
기능 있는 자신의 유형이 자동으로 유추한다.