forwardRef with defaultProps in Typescript

Viewed 1357

I'm trying to use defaultProps in forwardRef. When I use MessageBox without forwardRef it works well with defaultProps. But, when I use forwardRef with it an error occurs. how to solve it?

typescript: 3.4.5 "react": "^16.8.6",

import React, { forwardRef } from "react";

export interface MessageBoxProps {
  test: string;
  children: any;
}

const defaultProps: Partial<MessageBoxProps> = {
  test: "test"
};

const MessageBox = forwardRef<HTMLDivElement, MessageBoxProps>((props, ref) => {
  return <p>{props.test}</p>;
});

MessageBox.defaultProps = defaultProps;

export default MessageBox;

export default function App() {
  const ref = React.useRef<HTMLDivElement>(null);
  return (
    <div className="App">
      <Test ref={ref} />
    </div>
  );
}
Type '{ ref: RefObject<HTMLDivElement>; }' is missing the following properties from type 'MessageBoxProps': test, children

https://codesandbox.io/s/forwardref-with-typescript-knhu3?file=/src/App.tsx:83-244

1 Answers
Related