maslianok / react-resize-detector

A Cross-Browser, Event-based, Element Resize Detection for React
http://maslianok.github.io/react-resize-detector/
MIT License
1.25k stars 91 forks source link

Regression in withResizeDetector typing #150

Closed grasshoppergn closed 3 years ago

grasshoppergn commented 3 years ago

Hi! Great library, using it for a while already, absolutely love it, great job! :)

But with version 6.0.0+ one thing broke for me - in DefinitelyTyped version of withResizeDetector HoC, it is typed as

function withResizeDetector<T extends Partial<ReactResizeDetectorDimensions>>(
    WrappedComponent: React.ComponentType<T>,
    props?: ReactResizeDetectorProps,
): React.ComponentType<Omit<T, keyof ReactResizeDetectorDimensions>>;

but in the current version, it is

function withResizeDetector<P>(
  ComponentInner: ComponentType<P>,
  options?: ComponentsProps
): React.ForwardRefExoticComponent<React.PropsWithoutRef<P> & React.RefAttributes<HTMLElement>>;

In the result, the HoC that is created requires "width", "height", and "targetRef" props, if they are used in the internal component - and they are.

maslianok commented 3 years ago

Hi @grasshoppergn

You can remove DefinitelyTyped typings since v6 rewritten using typescript and contains types by default. This is mentioned in the Readme

Let me know if you have any additional questions

grasshoppergn commented 3 years ago

Hi @maslianok

Yes, I saw that they are obsolete. I'm just saying it's harder to get a useable component with withResizeDetector with current typings. Let's say we have the next code:

import React from "react";
import { withResizeDetector } from "react-resize-detector";

interface MyProps {
  width: number;
  height: number;
  targetRef: React.RefObject<HTMLDivElement>;
}

export const MyComponent = withResizeDetector(function MyComponent(props: MyProps) {
  return (
    <div ref={props.targetRef}>
      width: {props.width}
      height: {props.height}
    </div>
  );
});

export function MyOtherComponent() {
  return <MyComponent />;
}

TS reports an error, because MyComponent requires width, height, and targetRef.

So I should either declare them optional in MyProps and handle the case when they are undefined in MyComponent or do a as any as something cast in const MyComponent = to tell it that it actually doesn't need width and height to be passed to it by the users.

This code works fine with typings from previous version though.