Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript types for React Native's measure callback within a onLayout event?

How can I add TypeScript types to a measure callback within the onLayout event?

  <View
    ref={containerViewRef}
    onLayout={() => {
      if (containerViewRef.current) {
        containerViewRef?.current?.measure(
          (x, y, width, height, pageX, pageY): MeasureOnSuccessCallback => {
            setPageY(pageY);
          },
        );
      }
    }}
  >

measure has this error:

TS2339: Property 'measure' does not exist on type 'never'.

And MeasureOnSuccessCallback has this error:

TS2355: A function whose declared type is neither 'void' nor 'any' must return a value.

like image 997
Evanss Avatar asked Oct 25 '25 05:10

Evanss


1 Answers

Using the following package versions:

    "@types/react": "^16.9.2",
    "@types/react-native": "^0.60.25",
    "typescript": "^3.7.3"

the following snippet produces no errors:

const Test = () => {
  const containerViewRef = useRef<View>(null);

  const [, setPageY] = useState(0);

  return (
    <View
      ref={containerViewRef}
      onLayout={() => {
        containerViewRef.current?.measure(
          (x, y, width, height, pageX, pageY) => {
            setPageY(pageY);
          },
        );
      }}
    />
  );
};

Changes you need:

1) annotate your ref as const containerViewRef = useRef<View>(null);

2) remove MeasureOnSuccessCallback type annotation - it will be inferred by TS. (In your example it annotates the return value of the callback and not the callback itself, as it should).

like image 62
Marek Lisik Avatar answered Oct 26 '25 19:10

Marek Lisik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!