7

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?

Yichz
  • 9,250
  • 10
  • 54
  • 92

2 Answers2

8

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.)

Matt McCutchen
  • 28,856
  • 2
  • 68
  • 75
  • but is this a correct way to do it? I haven't seen other places doing this – Yichz Sep 04 '18 at 19:49
  • 1
    Come to your own conclusion. There's a similar scenario [here](https://stackoverflow.com/questions/40731352), but I like your idea of referencing `JSX.IntrinsicElements["div"]` directly since its definition might change in future versions of React. – Matt McCutchen Sep 04 '18 at 19:55
  • I really like this solution, much cleaner than [others I tried](https://stackoverflow.com/a/45677919/8897307) imo – Jeremy Aug 25 '21 at 05:57
0

Intersection type:

type DivProps = JSX.IntrinsicElements['div'] & {
  marginX: string
  marginY: string
}
mindlid
  • 1,679
  • 14
  • 17