reactjs - Flera TypeScript-diskrimineringar baserade på olika egenskaper


Jag försöker bygga en komplex REACT-komponent som stöder olika användningsfall. För att förenkla dess användning vill jag implementera TypeScript-diskrimineringstyper för att bättre härleda props.

Det är inte användbart att posta hela exemplet, men jag kan visa dig ett enklare, vilket är följande:

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>
}

Som du kan se, inne i ExampleComp är intellisense utmärkt och fungerar jättebra. Problemet är när jag försöker använda ExampleComp.
Vad jag skulle förvänta mig är att när jag skriver <ExampleComp, tillåter intellisense bara props category och saleType, eftersom de andra inte kan existera utan att först definiera de två. MEN, istället föreslår det allt:

Så, frågan här är: vad missar jag som gör att intellisense inte fungerar korrekt även i props?

TS Playground-länk

Svar #1

Det är bara naturen hos IntelliSense. När du börjar ange några av kombinationerna av de nödvändiga egenskaperna kommer de föreslagna att begränsas till endast de som är tillämpliga för den nuvarande möjliga kombinationen:

Innan du lägger till några rekvisita:

Efter att ha lagt till några rekvisita: