Considering we have a React component that depending on different props can render either <button> or <a> or React Router <Link>
Not sure if it is even possible in this case but how can we overload this component to accept the correct props for each case?
const Button: FC<ButtonProps> = forwardRef(
(
{
className,
disabled,
onClick,
children,
href,
to,
downloadable,
...rest
},
ref
) => { ... }
In addition to some shared props, unique props combination in each case is
interface BaseProps {
bSize?: ButtonSize;
bType?: ButtonType;
bLayout?: ButtonLayout;
}
interface ButtonBaseProps extends ButtonHTMLAttributes<HTMLButtonElement> {
onClick?: (event: MouseEvent<HTMLButtonElement>) => void;
ref?: Ref<HTMLButtonElement>;
}
interface ExternalLinkProps extends AnchorHTMLAttributes<HTMLAnchorElement> {
onClick?: (event: MouseEvent<HTMLAnchorElement>) => void;
ref?: Ref<HTMLAnchorElement>;
href?: string;
downloadable?: boolean;
}
interface ReactRouterLinkProps
extends ForwardRefExoticComponent<LinkProps & RefAttributes<HTMLAnchorElement>> {
onClick?: (event: MouseEvent<HTMLAnchorElement>) => void;
ref?: Ref<HTMLAnchorElement>;
to?: string;
}
export type ButtonProps = BaseProps & (ButtonBaseProps | ExternalLinkProps | ReactRouterLinkProps);
Normally for a function, I would do something like this
function foo(bar: string[]): string[];
function foo(bar: number[]): number[];
function foo(bar: string[] | number[]): string[] | number[] { ... }
if...elseis what I am doing. As I said, will leave the question open anyway for learning something.