Description
🔎 Search Terms
"typescript destructuring losses types", "typescript destructuring losses type object is possibly undefined", "typescript type alias destructuring loses type", "typescript inference with union types"
🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ
⏯ Playground Link
💻 Code
type UseQueryResult<T> = {
isSuccess: false;
data: undefined;
} | {
isSuccess: true;
data: T
};
function useQuery(): UseQueryResult<number> {
return {
isSuccess: false,
data: undefined,
};
}
const { data: data1, isSuccess: isSuccess1 } = useQuery();
const { data: data2, isSuccess: isSuccess2 } = useQuery();
const { data: data3, isSuccess: isSuccess3 } = useQuery();
// It works as expected
if (isSuccess1 && isSuccess2 && isSuccess3) {
data1.toExponential();
data2.toExponential();
data3.toExponential();
}
const areSuccess = isSuccess1 && isSuccess2 && isSuccess3;
// It doesn't work here, while it's just a combination of 'successes'
if (areSuccess) {
data1.toExponential();
data2.toExponential();
data3.toExponential();
}
🙁 Actual behavior
The issue occurs when using the combined boolean variable areSuccess
in the second if condition. Although isSuccess1
, isSuccess2
, and isSuccess3
are all true, TypeScript cannot narrow down the types of data1
, data2
, and data3
within the if block, leading to a type error
🙂 Expected behavior
areSuccess
is a combination of the individual isSuccess
variables, it should correctly infer the types of data1
, data2
, and data3
as the specific data type (number) defined for the queries. This should allow the code to call the toExponential method on each data variable without any issues.
Additional information about the issue
No response