I have a react component that has 3 variants. I have my props typed like this:
enum VariantType {
VARIANT_1 = "variant_1",
VARIANT_2 = "variant_2",
VARIANT_3 = "variant_3",
}
type BaseProps = {
a: string;
}
type Variant1Props = BaseProps & {
variant: VariantType.VARIANT_1;
b: never;
}
type Variant2Props = BaseProps & {
variant: VariantType.VARIANT_2;
b: number;
}
type Variant3Props = BaseProps & {
variant: VariantType.VARIANT_3;
b: boolean;
}
export const FancyComponent: FunctionComponent<Variant1Props | Variant2Props | Variant3Props> = (props) => {
const someNumber = props.variant === VariantType.VARIANT_2 ? props.b : 123;
...
}
In the assignment of someNumber TS knows that b is defined because I checked the variant. When using the component TS complains when b is present when it's VARIANT_1 and it complains when b is not present/not a number when it's VARIANT_2 (same for VARIANT_3).
What I'm looking for now is a way to make the variant option optional when using the component and it should default to VARIANT_1 and you could set it to VARIANT_2 or VARIANT_3 without loosing any of the type-safety I have now.
I tried stuff with generics and so on but couldn't get it to work.
I'm using Typescript 4.5.