benjamin.keen
benjamin.keen

Reputation: 1984

Typescript HOC - requiring a prop on the React component

Ah, TS. I'm having trouble forcing an HOC to require all components that uses it to include a property. This is what I have:

interface ExpectedComponentProps {
    requiredProp: string;
    [other: string]: any;
}

const withRequiredProp = function<OriginalProps extends ExpectedComponentProps>(
    WrappedComponent: React.ComponentType<OriginalProps>
) {
    // here I know requiredProp is defined for the component
}

Example usage:

const MyNewComponent = withRequiredProp(MyComponent);

// this should be valid
// <MyNewComponent requiredProp="hello" />

// this should throw a TS error
// <MyNewComponent />

However, it doesn't enforce the requiredProp as I would expect it to. How did I mess up the syntax here?

Upvotes: 1

Views: 154

Answers (1)

jperl
jperl

Reputation: 5112

This seems to work

function withRequiredProp<C extends React.ComponentType<any>>(
  Component: C,
): React.ComponentType<ExpectedComponentProps> {
  return Component //we just return the argument but we said it was 
  // React.ComponentType<ExpectedComponentProps>
}

const MyComponent: React.FC = () => (
  <div>test</div>
);

const MyNewComponent = withRequiredProp(MyComponent);

Now, MyComponent doesn't enforce requiredProp. But MyNewComponent does.

<MyComponent /> //OK
<MyNewComponent /> //error
<MyNewComponent requiredProp="hello" /> //OK

Upvotes: 2

Related Questions