Pesquisa de site

typescript - Guardas de tipo definidos pelo usuário negativos


function isFish(pet: Fish | Bird): pet is Fish {
    return (<Fish>pet).swim !== undefined;
}

informa ao TypeScript que o tipo de animal de estimação é Peixe

Existe uma maneira de afirmar o contrário, que o parâmetro de entrada NÃO é um Peixe?

function isNotFish(pet: Fish | Bird): pet is not Fish {  // ????
       return pet.swim === undefined;
}

Resposta #1

Você pode usar o tipo condicional Exclude para excluir tipos de uma união :

function isNotFish(pet: Fish | Bird): pet is Exclude<typeof pet, Fish>    
{ 
    return pet.swim === undefined;
}

Ou uma versão mais genérica :

function isNotFishG<T>(pet: T ): pet is Exclude<typeof pet, Fish>    { 
    return pet.swim === undefined;
}
interface Fish { swim: boolean }
interface Bird { crow: boolean }
let p: Fish | Bird;
if (isNotFishG(p)) {
    p.crow
}

Artigos relacionados