Lee Developer
Lee Developer

Reputation: 98

how to declare the type in my functional component?

I wanted to declare the type in my component this way, I already saw that this is possible using classes, but how could I do it using functional components? Without having to export the interface? I have already researched a lot and found nothing about it.

const Elem1 = forwardRef((props : any, ref : { open()? : void }) => {
   useImperativeHandle(ref, () => ({
       open: () => console.log('opened')
   }))

   ....
})

const Elem2 = () => {
    const elem1Ref = useRef<Elem1>()

    elem1Ref?.current?.open()

    ....
}

Upvotes: 0

Views: 88

Answers (2)

Lee Developer
Lee Developer

Reputation: 98

I've been researching and from what they said, it is not possible to declare the type of a functional component, just by exporting the component's separate interface, thanks anyway!

Upvotes: 0

Gilson Cavalcanti
Gilson Cavalcanti

Reputation: 1513

If i got right, you should use the type parameters provided by the TS Generics definition of forwardRef. Like this 👇

const Elem1 = forwardRef<YourRefType, YourPropsType>((props, ref) => {
  ...
}

Upvotes: 1

Related Questions