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:
So, the question here is: what am I missing that does not make the intellisense works correctly ALSO in the props?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.