'How to iterate over React children and access their ref in a helper function with TypeScript?

I am trying to learn how to perform more complex browser animations and would like to experiment with the FLIP methodology. I found this blog post https://medium.com/ft-product-technology/animating-list-reordering-with-react-hooks-1aa0d78a24dc that achieves an affect very similar what I want but I cannot work out how to translate the calculateBoundingBoxes helper function into TypeScript.

Attempting to access child.ref has the TypeScript error:

Property 'ref' does not exist on type 'string | number | boolean | {} | ReactElement<any, string | JSXElementConstructor<any>> | ReactPortal'.
  Property 'ref' does not exist on type 'string'.

How do I correctly type this function such that it only accepts children that all have refs?

const calculateBoundingBoxes = (children: ReactNode) => {
  const boundingBoxes = {};

  React.Children.forEach(children, (child) => {
    if (child == null) {
      throw new Error()
    }

    const domNode = child.ref.current;
    const nodeBoundingBox = domNode.getBoundingClientRect();

    boundingBoxes[child.key] = nodeBoundingBox;
  });

  return boundingBoxes;
};

Thank you!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source