type ButtonVariant = 'action' | 'hero';
type Size = 'small' | 'medium' | 'large';
export interface ButtonProps {
variant: ButtonVariant;
size?: Size;
}
export default function Button(props: ButtonProps): ReactElement {
const { variant } = props;
if (variant === 'hero')) {
return <HeroButton {...props} />;
}
if (variant === 'pill') {
return <PillButton {...props} />;
}
}
In the above code, I have two variants of a React button: HeroButton and PillButton.
Both buttons expect "ButtonProps" as their prop type. However, I would like to make HeroButton only expect a size of "medium" or "large". PillButton should accept "small", "medium" or "large" as its size prop.
Question: how can I write the ButtonProps interface such that the Button component allows (and suggests in VS Code) 'small' | 'medium' | 'large' as the size prop when the variant prop is "pill", but only allows 'medium' | 'large' when the variant prop is "hero"?
Note: I've looked into TypeScript Discriminated Unions to solve this, but haven't managed to get it working.