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

Viewed 1351

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.

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).

Related