Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript how to extend native HTML element?

Let's say I want to create a custom div component call MyDiv with additional attributes, eg.

interface MyDivProps {
  marginX: string;
  marginY: string;
}

but I still want to have all the type checking for regular HTMLDivElement, so what I want is actually something like:

interface MyDivProps implements JSX.IntrinsicElement.div {
      marginX: string;
      marginY: string;
    }

(I use JSX.IntrinsicElement.div instead of HTMLDivElement because it has additional React div attribute such as ref)

Obviously this won't work because interface cannot implements another interface, also IntrinsicElements is not exposed.

What would be the correct way to do this?

like image 974
Yichaoz Avatar asked Sep 04 '18 19:09

Yichaoz


1 Answers

The syntax you are looking for is:

type DivProps = JSX.IntrinsicElements["div"];
interface MyDivProps extends DivProps {
  marginX: string;
  marginY: string;
}

(TypeScript has a restriction that an interface can only extend a dotted name, so you have to define a type alias for JSX.IntrinsicElements["div"] before you can extend it.)

like image 72
Matt McCutchen Avatar answered Nov 16 '22 21:11

Matt McCutchen