Skip to content
PROD v3.0.0-alpha

Alex Carpenter ¬

UI Engineer at Clerk

TypeScript snippets

Collection of useful TypeScript snippets

Array subset type

let arr1 = ["one", "two", "three"] as const;

type ArraySubset<T extends readonly string[]> = T[number][];

let arr2: ArraySubset<typeof arr1> = ["one", "two"]; // No error
let arr3: ArraySubset<typeof arr1> = ["one", "two", "four"]; // Errors because 'four' is not within arr1

forwardRef function

The same as React.forwardRef but passes the ref as a prop and returns a component with the same generic type.

export function forwardRef<T extends React.FC<any>>(render: T) {
  const Role = React.forwardRef((props, ref) => render({ ...props, ref }));
  Role.displayName = render.displayName || render.name;
  return Role as unknown as T;
}

via Ariakit


Polymorphic button

function Button<T extends keyof React.JSX.IntrinsicElements>({
  as,
  ...props
}: React.ComponentProps<T> & { as: T }): React.ReactNode {
  return React.createElement(as, props);
}
type ButtonOrLinkProps =
  | (React.JSX.InstrinsicElements["button"] & { href?: undefined })
  | (React.JSX.IntrinsicElements["a"] & { href: string });

function Button(props: ButtonOrLinkProps) {
  if (props.href !== null) {
    return <a {...props} />;
  }
  return <button {...props} />;
}

via mattpocockuk