6
I realized that by performing the breakdown in the signature of the function (funcao({ a, b }: Objeto)
), I end up losing a certain consistency of the types. In the specific case where I realized this, always only one of the properties is defined (a
or b
), but when performing the de-structuring, Typescript "forgets" this.
For example:
type CatsOrDogs =
| { cats: string[]; dogs?: undefined }
| { cats?: undefined; dogs: string[] };
// Funciona
function test(obj: CatsOrDogs) {
if (obj.cats !== undefined) {
obj.cats.push('');
} else {
obj.dogs.push('');
}
}
// Não funciona
function testDestructuring({ cats, dogs }: CatsOrDogs) {
if (cats !== undefined) {
cats.push('');
} else {
dogs.push(''); // Object is possibly 'undefined'.(2532)
}
}
See on Playground.
How can I raise this guy
CatsOrDogs
without losing consistency in structuring?Or, there is another way to have the desired behavior without giving up the use of destructuring?
Interestingly I made one ask about it in Soen there is a time. v
– Luiz Felipe