Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do you pass a generic type to an anonymous function in typescript tsx file

The following function is failing in a .tsx file:

export const withComponent = <T>(Component: React.ComponentType<T>) => (props: any) => (
  <shortcutContext.Consumer>
    {addShortcut => <Component addShortcut={addShortcut} {...props} />}
  </shortcutContext.Consumer>
);

With the error JSX element 'T' has no corresponding closing tag.

like image 944
dagda1 Avatar asked Oct 15 '25 14:10

dagda1


2 Answers

Looks like a limitation of .tsx parser, there is no way to make it interpret this particular < as a delimiter for generic parameter instead of start tag.

But for this particular case, the workaround is easy.

export const implies this is at the top level, and its implementation does not refer to this anyway, so it could be rewritten using an old-style function instead of the first =>:

export const withComponent = function<T>(Component: React.ComponentType<T>) { 
    return (props: any) => (
        <shortcutContext.Consumer>
            {addShortcut => <Component addShortcut={addShortcut} {...props} />}
        </shortcutContext.Consumer>
    )
};
like image 50
artem Avatar answered Oct 17 '25 19:10

artem


you could write this way as well:

export const withComponent = <T,>(Component: React.ComponentType<T>) => (props: any) => (
  <shortcutContext.Consumer>
    {addShortcut => <Component addShortcut={addShortcut} {...props} />}
  </shortcutContext.Consumer>
);
like image 43
nshathish Avatar answered Oct 17 '25 20:10

nshathish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!