Multiple TypeScript discriminations based on different properties

Viewed 48

I'm trying to build a complex REACT component which supports different use-cases. In order to simplify its use, I want to implement TypeScript discriminations types to better infer the props.

It's not useful to post the full example, but I can show you a simpler one, which is the following one:

interface ICategoryDiscriminationGame {
    category: 'game';
    gameType: 'AAA' | 'AA' | 'A';
}

interface ICategoryDiscriminationProgram {
    category: 'program';
    programType: 'software' | 'freeware';
}

type TCategoryDiscrimination = (ICategoryDiscriminationGame | ICategoryDiscriminationProgram);


interface ISaleDiscriminationPresale {
    saleType: 'pre-sale',
    preSaleCost: number;
}

interface ISaleDiscriminationRetailSale {
    saleType: 'retail',
    retailSaleCost: number;
}

type TSaleDiscrimination = (ISaleDiscriminationPresale | ISaleDiscriminationRetailSale);


type TExampleCompProps = TCategoryDiscrimination & TSaleDiscrimination;

export const ExampleComp = (props: TExampleCompProps) => {
    if (props.category === 'game') { // In here, intellisense infer only use 'props.category' and 'props.saleType' -> NICE
        console.log(props.gameType); // In here, intellisense infer also 'props.gameType' -> NICE
    }

    if (props.saleType === 'pre-sale') { // In here, intellisense infer only use 'props.category' and 'props.saleType' -> NICE
        console.log(props.preSaleCost); // In here, intellisense infer also 'props.preSaleCost' -> NICE
    }

    if (props.category === 'game' && props.saleType === 'retail') { // In here, intellisense infer only use 'props.category' and 'props.saleType' -> NICE
        console.log(props.retailSaleCost); // In here, intellisense infer also 'props.retailSaleCost' and 'props.gameType' -> NICE
        console.log(props.gameType); // In here, intellisense infer also 'props.retailSaleCost' and 'props.gameType' -> NICE
    }

    return <p>In example comp</p>
}

As you can see, inside the ExampleComp, the intellisense is brilliant, and works great. The problem is when I try to use the ExampleComp.
What I would expect is that, when I write <ExampleComp, the intellisense allows me only the props category and saleType, since the other ones cannot exist without first defining those two. BUT, instead, it just suggests everything:

enter image description here

So, the question here is: what am I missing that does not make the intellisense works correctly ALSO in the props?

TS Playground link

1 Answers

That's just the nature of IntelliSense. Once you start to supply some of the combinations of the required props, the suggested ones will be narrowed to only the ones which are applicable to the current possible combination:

Before adding some props: Before adding some props

After adding some props: After adding some props

Related