til

What's the difference between DetailedHTMLProps and HTMLAttributes

typescript

I came across a tweet of cpojer where he claimed he liked the native browser form validation and in the snippet I found a TypeScript utility I haven't seen before: React.DetailedHTMLProps. It seems it's like React.HTMLAttributes but it also adds key and ref as optional props.

function App() {
  return (
    <div className="App">
      <Form>
        <label htmlFor="name">Name:</label>
        <input name="name" placeholder="Type here your name" required />
      </Form>
    </div>
  );
}

type FormProps = React.DetailedHTMLProps<
  React.FormHTMLAttributes<HTMLFormElement>,
  HTMLFormElement
>;

function Form({ onBlur: onBlurBase, ...rest }: FormProps) {
  const onBlur: React.FocusEventHandler<HTMLFormElement> = (e) => {
    e.target.classList.add("validate");
    onBlurBase?.(e);
  };

  return <form {...rest} onBlur={onBlur} />;
}

If you want to play with the code above you can do it here.

I found the answer to my question in Stackoverflow thanks to Marcin. I copy here the response because it's worthwile knowing it.

interface ComponentProps1
  extends React.DetailedHTMLProps<
    React.HTMLAttributes<HTMLDivElement>,
    HTMLDivElement
  > {}

interface ComponentProps2 extends React.HTMLAttributes<HTMLDivElement> {}
type Dif = Omit<ComponentProps1, keyof ComponentProps2>;
type Dif = {
  ref?: LegacyRef<HTMLDivElement>;
  key?: string | number;
};

I learnt this from @cpojer