我想创建一个函数,它可以获得一个可选的errorCallback
参数.如果该函数的使用者没有提供回调,我想使用缺省回调.此函数需要强类型,并使用消费者自定义的errorCallback
‘S返回类型的返回类型,否则使用我的自定义错误处理程序的返回类型.
以下是代码:
export enum ErrorType {
VALIDATION_ERROR,
API_ERROR,
UNKNOWN_ERROR,
UNAUTHORIZED
}
type MockZodType ={}
type MockResponseError = {}
export type ServiceError<TSchema extends MockZodType> =
| {
type: ErrorType.VALIDATION_ERROR;
message: string;
status: number;
data: TSchema;
originalError: MockResponseError;
}
| {
type: ErrorType.API_ERROR;
message: string;
status: number;
data: unknown;
originalError: MockResponseError;
}
| {
type: ErrorType.UNKNOWN_ERROR;
message: string;
status: number;
data: unknown;
originalError: unknown;
}
| {
type: ErrorType.UNAUTHORIZED;
message: string;
status: number;
data: unknown;
preventDefaultHandler: boolean;
originalError: MockResponseError;
};
export type ServiceCallOptions<
TServiceCallReturn extends Promise<unknown>,
TSchema extends MockZodType = never,
TErrorCallbackReturn extends Promise<unknown> = Promise<ServiceError<TSchema>>
> = {
serviceCall: () => TServiceCallReturn;
errorSchema?: TSchema;
errorCallback?: (e: ServiceError<TSchema>) => TErrorCallbackReturn;
};
export async function callService<
TServiceCallReturn extends Promise<unknown>,
TSchema extends MockZodType = never,
TErrorCallbackReturn extends Promise<unknown> = Promise<ServiceError<TSchema>>
>({
serviceCall,
errorSchema,
errorCallback = async (e)=> {
if (e.type === ErrorType.UNAUTHORIZED && !e.preventDefaultHandler) {
// some custom default handler;
}
return e;
}
}: ServiceCallOptions<TServiceCallReturn, TSchema, TErrorCallbackReturn>) {
// some logic
}
错误来自errorCallback
的默认参数值,当它说:
Type '(e: ServiceError<TSchema>) => Promise<ServiceError<TSchema>>' is not assignable to type '(e: ServiceError<TSchema>) => TErrorCallbackReturn'.
Type 'Promise<ServiceError<TSchema>>' is not assignable to type 'TErrorCallbackReturn'.
'Promise<ServiceError<TSchema>>' is assignable to the constraint of type 'TErrorCallbackReturn', but 'TErrorCallbackReturn' could be instantiated with a different subtype of constraint 'Promise<unknown>'.
我不想使用超载.为什么这不管用呢?
这是ts playground的链接.