Is there anyone who can assist me in comprehending the scenario below:
export function functionThatReturnsTurpleObjects():
| [{ a: number }, undefined]
| [undefined, { a: number }]
{
if (Math.random() > 0.5) {
return [undefined, { a: 1 }];
}
return [{ a: 1 }, undefined];
}
function execute1() {
const [res1, res2] = functionThatReturnsTurpleObjects();
if (res2) {
return res2;
}
// res1 cannot be undefined and TypeScript recognizes it
res1.a;
}
function functionThatReturnsTurpleObjectAndString():
| [{ a: number }, undefined]
| [undefined, string] {
if (Math.random() > 0.5) {
return [undefined, "1"];
}
return [{ a: 1 }, undefined];
}
function execute2() {
const [res1, res2] = functionThatReturnsTurpleObjectAndString();
if (res2) {
return res2;
}
// res1 cannot be undefined but TypeScript throws error "TS18048: res1 is possibly undefined"
res1.a;
}
I would anticipate that both scenarios should function identically.