Skip to content

Instantly share code, notes, and snippets.

@mateusvahl
Last active March 20, 2024 13:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mateusvahl/a3e1b351cada6c2e2daf35482ed1eded to your computer and use it in GitHub Desktop.
Save mateusvahl/a3e1b351cada6c2e2daf35482ed1eded to your computer and use it in GitHub Desktop.
React / Typescript Dynamic tag with intellisense autocomplete
import { ReactNode, ElementType, ComponentPropsWithoutRef } from "react";
export type Prefer<P, T> = P & Omit<T, keyof P>;
export type ElementPropsWithoutRef<T extends ElementType> = Pick<
ComponentPropsWithoutRef<T>,
keyof ComponentPropsWithoutRef<T>
>;
export type OverwritableType<OwnProps, Type extends ElementType> = Prefer<
OwnProps,
ElementPropsWithoutRef<Type>
>;
interface Props<T> {
as?: T;
children?: ReactNode;
}
// 'button' is a default value
function Box<T extends ElementType = "button">({
as,
children,
...rest
}: OverwritableType<Props<T>, T>) {
const Tag: ElementType = as;
return (
<Tag {...rest}>
{children}
</Tag>
);
}
export default Box;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment