Patrickkx
Patrickkx

Reputation: 1870

Typescript - forward and useref

I have two components:

const ComponentOne = () => {
   const a = React.useRef<ComponentTwo>(null);
                // ^^^^^^^^^^ throws error - ComponentTwo refers to a value but used as type here
   const fn = () => {
      a.current.open(); // how to type it so typescript knows than open() is a function

      a.current.awdokawd(); // typescript should throw error here
   };

   return (
      <ComponentTwo ref={a} />
   );
}

const ComponentTwo = React.forwardRef((props, ref: React.RefObject<What here?>) => {
                                                            // ^^^^ what to type here?
   React.useImperativeHandle(ref, () => ({
      open: () => {
         console.log('hey');
      },
   }));

   return (
      ...
   );
});

So as you can see, Im not sure what to enter with useRef so typescript properly recognizes the component and its method. Also not sure what to type with forwardRef.

Thanks!

Upvotes: 1

Views: 1743

Answers (1)

emeraldsanto
emeraldsanto

Reputation: 4741

You simply have to declare a new type for the ref:

interface ComponentTwoRef {
    open(): void;
}

const ComponentOne = () => {
   const a = React.useRef<ComponentTwoRef>(null);

   const fn = () => {
      a.current.open();

      a.current.awdokawd(); // typescript should throw error here
   };

   return (
      <ComponentTwo ref={a} />
   );
}

const ComponentTwo = React.forwardRef((props, ref: React.RefObject<ComponentTwoRef>) => {

   React.useImperativeHandle(ref, () => ({
      open: () => {
         console.log('hey');
      },
   }));

   return (
      ...
   );
});

Upvotes: 4

Related Questions