Hey everyone could somebody help me to understand the following situation:
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 can't be undefined and ts understand 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 can't be undefined but ts throws error "TS18048: res1 is possibly undefined"
res1.a;
}
link to playground
I would expect that both cases should work in the same way.
New contributor
Evgeniy Lyahov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.