He estado intentando pero no he logrado que este tipo de unión funcione como quiero, ¿esto simplemente no es compatible?
type TestA = { href: string; a: string };
type TestB = { href?: never; b: string };
type TestUnion = TestA | TestB;
const test = (x: TestUnion) => {
if (x.href) {
console.log("X is TestA", x.a);
} else {
console.log("x should be TestB, but is TestUnion", x.b); // error
}
};
Solución del problema
En
const testBad = (x: TestUnion) => {
if (x.href) {
console.log("X is TestA", x.a.toUpperCase());
} else {
console.log("x should be TestB, but is TestUnion",
x.b.toUpperCase());
//~ <-- error, property b does not exist on TestA
}
};
el tipo de x.hrefcomienza como string | undefined. Usar (x.href)como condición en una ifdeclaración es realizar una verificación de veracidad. Y mientras que una verdad x.hrefimplica que x.hrefpuede reducirse a string, una falsedad x.href no implica que x.hrefpueda reducirse a undefined, porque la cadena vacía ""es falsa.
Por lo tanto, puede ingresar al elsebloque con un TestAsin querer como este:
testBad({ href: "", a: "" }); // compiles, but
// RUNTIME ERROR
No hay comentarios:
Publicar un comentario