typescript - Protectores de tipo de múltiples niveles
Dado el siguiente código, ¿cómo puedo modificar el guardia de tipos isAppErrorOfKind para que el tipo de retorno sea AppErrorHttp o AppErrorNetwork según el kind especificado?
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;
}
Respuesta #1
Necesitas inferir el argumento 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
}
}
Parque infantil
Respuesta #2
Si he entendido correctamente tu pregunta, quizás usaría una restricción de tipo genérico:
function isAppErrorOfKind<T extends AppError>(error: T, kind: AppError["kind"]): error is T {
if (!isAppError(error)) return false;
return error.kind === kind;
}
Luego solo puedes pasar un error del tipo AppError, que extienda AppErrorHttp y AppErrorNetwork.
