reactjstypescriptframer-motion

How to derive element type from motion component (m.div -> HTMLDivElement)?


Given a motion component, such as m.div is it possible to derive HTMLDivElement? Or, HTMLButtonElement from m.button, etc?

Perhaps a type utility that could do something like this?

type HTMLType = ToHTML<typeof m.div>;

I'm using framer-motion@12.11.0


Solution

  • Yes, it is doable and rather straightforward:

    import { m } from 'framer-motion'
    import { RefAttributes } from 'react'
    
    type ToHTML<MototionEl> = MototionEl extends (x: RefAttributes<infer DomEl>) => any ? DomEl : never
    
    type Div = ToHTML<typeof m.div>
    
    type Button = ToHTML<typeof m.button>
    
    type A = ToHTML<typeof m.a>
    

    enter image description here

    PLAYGROUND