Limiting Props a Component Can Take Based on Other Props
If you want to play along locally, you can use projects/buttons-base
in the project repository.
Let's say we have some buttons and we want to give them an API that looks like the following:
<Button primary>Primary</Button>
<Button secondary>Secondary</Button>
<Button destructive>Destructive</Button>
But, we want to disallow the ability for more than one of those properites to be passed.
We could create the following type:
type ButtonProps = {
children: string;
};
type PrimaryButtonProps = ButtonProps & { primary: boolean };
type SecondaryButtonProps = ButtonProps & { secondary: boolean };
type DestructiveButtonProps = ButtonProps & { destructive: boolean };
We can do something like this:
type ButtonProps = {
children: string;
};
type PrimaryButtonProps = {
primary: boolean;
secondary?: never;
destructive?: never;
};
type SecondaryButtonProps = {
primary?: never;
secondary: boolean;
destructive?: never;
};
type DestructiveButtonProps = {
primary?: never;
secondary?: never;
destructive: boolean;
};
You can find a completed version here.
Where Are We Now?
examples/36-buttons-with-limited-props
projects/buttons-base
on thebuttons-with-limited-props
branch- CodeSandbox