Getting "Support for defaultProps in JSX" to work with higher-order components

23 views Asked by At

TypeScript 3.0 introduced built-in support for defaultProps.

The example given there works fine in my project:

export interface Props {
  name: string;
}
export class Greet extends React.Component<Props> {
  render() {
    const { name } = this.props;
    return <div>Hello {name.toUpperCase()}!</div>;
  }
  static defaultProps = { name: "world" };
}
// Type-checks! No type assertions needed!
let el = <Greet />;

However, now let's introduce a HOC:

export interface Props {
  name: string;
}
export class Greet extends React.Component<Props> {
  render() {
    const { name } = this.props;
    return <div>Hello {name.toUpperCase()}!</div>;
  }
  static defaultProps = { name: "world" };
}

function withHOC<TProps>(Component: React.ComponentType<TProps>) {
  // eslint-disable-next-line react/function-component-definition
  return function ComponentHOC(props: TProps) {
    return (
      <Component {...props} />
    );
  };
}

const GreetHOC = withHOC(Greet);
// Doesn't type check!
let el = <GreetHOC />;

Here I see

Property 'name' is missing in type '{}' but required in type 'Props'.

How can I change withHOC to get it to work?

Demo app: https://stackblitz.com/edit/react-ts-ijf9bq?file=index.tsx

I found https://github.com/typescript-cheatsheets/react/issues/86#issuecomment-822911042, but the example given there as a "working version" doesn't seem to compile now.

0

There are 0 answers