我有一个功能需要采取一种任意的同步功能和返回的结果的等待,同步功能,但包装在一个尝试/抓住其中增加了一些额外的逻辑。 看到 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
功能有它们的类型自动地推断出我。