VSCode TS error with React.forwardRef functional component

Viewed 234

We are using JavaScript (not TypeScript) to write our component library, and we have checkJs: true in our project's jsconfig.json file.

All of our components are functional components (no class components). When a component requires a ref, we use React.forwardRef.

An example of a component for the sake of this question; not an actual component, but shows how we write our components:

import React from 'react';
import { View } from 'react-native';
import propTypes from './propTypes';

export const Box = React.forwardRef(({ padding, children }, ref) => {
  return (
    <View ref={ref} style={{ padding }}>
      {children}
    </View>
  );
});

Box.propTypes = propTypes;

However, this causes this "red squiggly line" error under the padding prop:

Property 'padding' does not exist on type '{ children?: ReactNode; }'.ts(2339)

And where the propTypes is assigned:

Type '{ padding: Requireable; }' has no properties in common with type 'WeakValidationMap<RefAttributes>'.ts(2559)

And when implementing this <Box> component, the red squiggly line appears under the component's name, and the error is:

Type '{ children: Element; }' has no properties in common with type 'IntrinsicAttributes & RefAttributes'.ts(2559)

The code itself is valid, and changing checkJs to false resolves this, but we want to keep checkJs true.

What exactly are we doing wrong?

1 Answers

I'm not sure what you're doing with propTypes, but you can define both the props and the ref type by setting the generics on forwardRef:

export const Box = React.forwardRef<View, {padding?: string | number}>(({ padding, children }, ref) => {
  return (
    <View ref={ref} style={{ padding }}>
      {children}
    </View>
  );
});

Playground Link

Related