microsoft/TypeScript

Partial Discriminated Union cannot always be narrowed

Closed this issue ยท 3 comments

๐Ÿ”Ž Search Terms

narrow partial discriminated union

๐Ÿ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about union types

โฏ Playground Link

https://www.typescriptlang.org/play/?ts=6.0.0-dev.20251022#code/KYOwrgtgBAKgngB2AZygbwFBW1AYge3ygF4oByAM0LIBoscAhAQwCcTyAjV2jAXwwwBLEABdgLCkwDGwPIQAKrJhGBiWqTDihMECADaCpTEYPwh4SAFyxEKAHQF8AbnrYq+a+AgdxL-kNFxSRkoZhZFFmVVcQ1XbV0DIxMzC2BrVOQ7MJctLhZPSB8WPwERWygI5VRSR0qVNVQAH1DWOuj1FwEKMBApZJAoMWQRAH0QMxGEVhMmPRGAE3wUMdYWfAB3AAoEazrkAEp0OMEKKG27HX1DY1NzcuIHqB754AphYHmoRuaEC4Tr-qpEiPDIOQiHTRaHAsVRgFggHI4fxaKRmZD4PTAOx6fAAc3OeX2iKhJIA9KSoAA9AD8fC6PT6t0GKFGUxYMzmi2W41GIFWG22u2mglmAB49gA+CHHU7nS6JG4pe6PZ6vd6fb5QX7ygG3IEPUigxzSknYGEiOEIuLInCokDozHYvEE1hEuKm7Dkqm0-wYbq9frM4aTYWzBZLZArFhrLY7CqhvTipQQZBSo5aE5nbX-JJ68oAQhBtkyYRNpvNluJUBt2DtDqxOPxv0JVY9UC9NLpQA

๐Ÿ’ป Code

enum Types {
    Foo = 'foo',
    Bar = 'bar',
}

interface FooParameters {
    applicationType: Types.Foo;
    foo: number;
}

interface BarParameters {
    applicationType: Types.Bar;
    bar: number;
}

type Params = FooParameters | BarParameters;


function test_non_partial_does_narrow(p: Params) {
    if (p.applicationType === undefined || p.applicationType === Types.Foo) {
        return;
    }

    console.log(p.bar);
             // ^? BarParameters
}

function test_partial_does_not_narrow(p: Partial<Params>) {
    if (p.applicationType === undefined || p.applicationType === Types.Foo) {
        return;
    }

    console.log(p.bar);
             // ^? Partial<Params>
}


function test_partial_does_narrow(p: Partial<Params>) {
    if (p.applicationType !== Types.Bar) {
        return;
    }

    console.log(p.bar);
             // ^? Partial<BarParameters>
}

๐Ÿ™ Actual behavior

The Partial<Params> discriminated union can only be narrowed if you return when it does not equal the expected value. When ruling out all other possibilities it does not narrow the type.

๐Ÿ™‚ Expected behavior

It also narrows the type, when ruling out all other possibilities

Additional information about the issue

No response

I believe this is a duplicate of #31404.

๐Ÿค– Thank you for your issue! I've done some analysis to help get you started. This response is automatically generated; feel free to ๐Ÿ‘ or ๐Ÿ‘Ž this comment according to its usefulness.

Similar Issues

Here are the most similar issues I found

If your issue is a duplicate of one of these, feel free to close this issue. Otherwise, no action is needed.

This issue has been marked as "Duplicate" and has seen no recent activity. It has been automatically closed for house-keeping purposes.