Solución
solution.tsTypeScript
interface ApiResponse {
data: string;
status: number;
ok: boolean;
}
export function isApiResponse(val: unknown): val is ApiResponse {
// Verifica que val sea un objeto con las propiedades correctas:
// - data debe ser de un tipo primitivo textual
// - status debe ser de un tipo primitivo numérico
// - ok debe ser de un tipo primitivo lógico
// Declara el tipo de retorno como predicado para estrechar el tipo
if( val !== null && typeof val === 'object') {
if( !val.hasOwnProperty( 'data') || typeof val['data'] !== 'string') {
return false;
}
if( !val.hasOwnProperty( 'status') || typeof val['status'] !== 'number') {
return false;
}
if( !val.hasOwnProperty( 'ok') || typeof val['ok'] !== 'boolean') {
return false;
}
// const apiResponse = val; => apiResponse: object
// const apiResponse = val as ApiResponse; => apiResponse: ApiResponse
return true;
}
return false;
}0respuestas