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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With