给定以下代码,如何修改isAppErrorOfKind类型保护,以便根据指定的kind返回类型为AppErrorHttp或AppErrorNetwork?
type AppError = AppErrorHttp | AppErrorNetwork | AppErrorUnsupported;
interface AppErrorHttp {
kind: 'http';
status: number;
}
interface AppErrorNetwork {
kind: 'network';
reason: string;
}
interface AppErrorUnsupported {
kind: 'unsupported';
api: string;
}
function isAppError(error: Error | AppError): error is AppError {
if (error === undefined || error === null) return false;
if (typeof(error) !== 'object') return false;
return 'kind' in error;
}
function isAppErrorOfKind(error: Error | AppError, kind: AppError['kind']): error is XXX {
if (!isAppError(error)) return false;
return error.kind === kind;
}发布于 2022-01-28 10:47:04
您需要推断kind参数:
type AppError = AppErrorHttp | AppErrorNetwork | AppErrorUnsupported;
interface AppErrorHttp {
kind: 'http';
status: number;
}
interface AppErrorNetwork {
kind: 'network';
reason: string;
}
interface AppErrorUnsupported {
kind: 'unsupported';
api: string;
}
function isAppError(error: Error | AppError): error is AppError {
if (error === undefined || error === null) return false;
if (typeof error !== 'object') return false;
return 'kind' in error;
}
function isAppErrorOfKind<Kind extends AppError['kind']>(
error: Error | AppError,
kind: Kind
): error is Extract<AppError, { kind: Kind }> {
if (!isAppError(error)) return false;
return error.kind === kind;
}
const foo = (arg: AppError) => {
if (isAppErrorOfKind(arg, 'network')) {
arg // AppErrorHttp
} else {
arg // AppErrorHttp | AppErrorUnsupported
}
}发布于 2022-01-28 10:09:22
如果我正确理解了您的问题,我可能会使用泛型类型约束:
function isAppErrorOfKind<T extends AppError>(error: T, kind: AppError["kind"]): error is T {
if (!isAppError(error)) return false;
return error.kind === kind;
}然后只能传入AppError类型的错误,扩展AppErrorHttp和AppErrorNetwork。
https://stackoverflow.com/questions/70891867
复制相似问题