Skip to content

Type inference fails when using combined boolean variable in if condition #55577

Closed
@ddubrava

Description

@ddubrava

🔎 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

https://www.typescriptlang.org/play?#code/C4TwDgpgBAqgzhAigVwgJxAJQnZAbYAHgBUA+KAXigG8AoKBqASzgGVkBjDnOALigBmAQzwIA3PUYATIcCH9kAOykQBTRRCkSAvlAA+NSQxbsuPfsDSoJjKDLn9itbRNoClHYEwD2iqMgQUdBAACgBKfngkVAxsXAJCRWQAWwAjdHI6WzQIYGQ0PyzbRhNObjg+QREEABojYvt5f2VVdU062xdnWloOXzhgGjtZJsaARhrmNjLzKdNyuDGoXSoA6ODwiT7FAaHG-kaAJknSswr+U4XD5cp-QJjQsK3+wephh3ehAGYT6bPKy48L43Vb3DZPHoAekhUAAkoMAO7eNAAazgUCE6IgAA9IJ5NLQmAIoCFARUlgAyClzGYVa5Umn-L5hQy2cYAOmA3gAorjfBBFF4RJt6kdOTy+RpBUxhRC2SMvuLeWB+dLZToettdkIcvMeLcyYsoAzDfTqYavq5oXDBlJvDhFAByRHIlFQAAW6AgkwR7qYeGgTGAjvRACsAoMhFA+ml1LIfH5vMSQ7SEHBHYTiSEdRA9RUWUUGByucrVUK8CL5XJDkrJQLy5XpArayqpQ2IdogA

💻 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Help WantedYou can do thisPossible ImprovementThe current behavior isn't wrong, but it's possible to see that it might be better in some cases

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions