How to allow certain combinations of props in React Typescript?

Viewed 251

I have two enums:

enum Drink = {
 WATER = 0,
 COFFEE = 1,
}

enum Sugar = {
 LITTLE = 0,
 ALOT = 1,
}

enum Temperature = {
 COLD = 0,
 HOT = 1,
}

I want to have a react component which will accept only certain combinations of this enums and reject the others.

For example I want to accept:

WATER & {HOT | COLD}
COFFEE & {LITTLE | ALOT}

but I want to reject:

WATER & SUGAR
or
COFFEE & COLD

I tried to make this type:

type someType = {
   drink: Drink.WATER
   temperature: Temperature.HOT | Temperature.COLD
} | 
{
   drink: Drink.COFFEE
   sugar: Sugar.LITTLE | Sugar.ALOT
}

but this is not nice.

I would like to have them as separate props and for example when the user tries to type:

<SpecificCompo drink={water} /*<-- here don't display sugar={} or if the user tries to type it, i want typescript to complain that type of water doesn't match with sugar --> */ />

Any help on this ?

1 Answers

enum Drink {
    WATER = 0,
    COFFEE = 1,
}

enum Sugar {
    LITTLE = 0,
    ALOT = 1,
}

enum Temperature {
    COLD = 0,
    HOT = 1,
}

interface BaseProps {
    // Whatever props
}

interface WaterProps extends BaseProps {
    drink: Drink.WATER,
    temperature: Temperature.HOT | Temperature.COLD
}

interface CoffeeProps extends BaseProps {
    drink: Drink.COFFEE,
    sugar: Sugar.LITTLE | Sugar.ALOT
}

export type ISpecificCompoProps = WaterProps | CoffeeProps;
Related