Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics error with forwardRef: Property 'ref' does not exist on type 'IntrinsicAttributes'

When using forwardRef with generics, I get Property 'children' does not exist on type 'IntrinsicAttributes' or Property 'ref' does not exist on type 'IntrinsicAttributes'.

https://codesandbox.io/s/react-typescript-0dt6d?fontsize=14

Relevant code in CodeSandbox link above replicated here:

interface SimpleProps<T extends string>
  extends React.HTMLProps<HTMLButtonElement> {
  random: T;
}

interface Props {
  ref?: React.RefObject<HTMLButtonElement>;
  children: React.ReactNode;
}

function WithGenericsButton<T extends string>() {
  return React.forwardRef<HTMLButtonElement, Props & SimpleProps<T>>(
    ({ children, ...otherProps }, ref) => (
      <button ref={ref} className="FancyButton" {...otherProps}>
        {children}
      </button>
    )
  );
}

() => (
  <WithGenericsButton<string> ref={ref} color="green">
    Click me! // Errors: Property 'children' does not exist on type 'IntrinsicAttributes'
  </WithGenericsButton>
)

A potential solution is suggested here but not sure how to implement in this context: https://github.com/microsoft/TypeScript/pull/30215 (Found from https://stackoverflow.com/a/51898192/9973558)

like image 842
Stephen Koo Avatar asked Sep 02 '19 02:09

Stephen Koo


1 Answers

So the main problem here is that you're returning the result of React.forwardRef in your render, which isn't a valid return type for the render func. You'd need to define the forwardRef result as it's own component, and then render that inside your WithGenericsButton higher order component, like so:

import * as React from "react";

interface SimpleProps<T extends string> {
  random: T;
}

interface Props {
  children: React.ReactNode;
  color: string;
}

function WithGenericsButton<T extends string>(
  props: Props & SimpleProps<T> & { ref: React.Ref<HTMLButtonElement> }
) {
  type CombinedProps = Props & SimpleProps<T>;
  const Button = React.forwardRef<HTMLButtonElement, CombinedProps>(
    ({ children, ...otherProps }, ref) => (
      <button ref={ref} className="FancyButton" {...otherProps}>
        {children}
      </button>
    )
  );
  return <Button {...props} />;
}

const App: React.FC = () => {
  const ref = React.useRef<HTMLButtonElement>(null);
  return (
    <WithGenericsButton<string> ref={ref} color="green" random="foo">
      Click me!
    </WithGenericsButton>
  );
};

If you put that in a sandbox or playground you'll see that props is now typed correctly including a random prop of T

like image 132
Matt D Avatar answered Sep 18 '22 21:09

Matt D