ฉันมีฟังก์ชันจะต้องเป็นเผด็จการซะหน่อ async ฟังก์ชันและจะคืนค่ากลับมาเป็นผลของซีนั่น async ฟังก์ชันแต่ห่อในพยายาม/จับซึ่งเพิ่มเพิ่มเติมตรรกะ. เห็น ts สนามเด็กเล่น.
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
ฟังก์ชันที่มีประเภทของโดยอัตโนมัติ inferred สำหรับฉัน