Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript - type parameter not recognized in tsx file?

I have an example file called "test.ts" with this code:

const test = <T>(a: string) => { return a; } ;

It works! If I rename the file to "test.tsx" then Visual Studio Code marks the T parameter with red, and gives the following error:

[ts] Cannot find name 'T'.

[ts] JSX element 'T' has no corresponding close tag.

I must use .tsx extension because the actual code needs to return JSX elements. I also must use type parameters. But how can I do both?

like image 737
nagylzs Avatar asked Oct 23 '25 08:10

nagylzs


1 Answers

Tsx and generic arrow functions don't mix well. The simplest solution is to use a regular function, since you don't capture this from the declaring context anyway:

const withLazyStatus = function<T>(WrappedComponent: React.ComponentType<ILazyState<T>>) {
    return class WithLazyStatus extends React.Component<ILazyState<T>> {
        // Enhance component name for debugging and React-Dev-Tools
        static displayName = `withLazyStatus(${WrappedComponent.name})`;

        render() {
            let props = this.props;
            if (props.fetching) {
                return loading;
            } else if (props.error) {
                return error(props.error);
            } else {
                return <WrappedComponent {...this.props} />;
            }
        }
    };
};

Or the other option is to add a type constraint :

 const withLazyStatus = <T extends object>(WrappedComponent: React.ComponentType<ILazyState<T>>) {
        return  ...
  };

The constraint will disambiguate the generic vs tag constructs

like image 186
Titian Cernicova-Dragomir Avatar answered Oct 25 '25 08:10

Titian Cernicova-Dragomir



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!