I'm trying to create a React component with conditional props using a piped type between two interfaces. I have it set up like this:
interface BaseProps {
"aria-label"?: string;
className?: string;
onClick?: () => void;
}
interface IconProps extends BaseProps {
"aria-label": string;
children: never;
icon: React.ReactElement;
}
interface ButtonProps extends BaseProps {
children: React.ReactElement;
}
type Props = ButtonProps | IconProps;
class Button extends React.Component<Props> {
render(): React.ReactElement {
const { children, icon, ...rest } = this.props;
// ERROR: "Property 'icon' does not exist on type '(Readonly<ButtonProps> & Readonly<{ children?: ReactNode; }>) | (Readonly<IconProps> & Readonly<{ children?: ReactNode; }>)'."
}
}
I can't seem to figure out how to achieve the following:
- When there is an "icon" prop, force "aria-label" and disallow children
- When there is not an "icon" prop, force children and allow optional "aria-label"