4

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?

1
  • Dunno, that answer cannot be accepted. I should post my own answer, and accept that. Doing it anyway... if I can. Commented Jan 30, 2018 at 14:22

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

3 Comments

Meanwhile, I figured out it myself but you posted it as an answer sooner. :-)
@nagylzs Still good for others to reference in the future :). I edited the answer after posting, and added the second option which also works well in you need arrow functions
<T extends object> is genius
0

TypeScript also uses angle brackets for type assertions so JSX’s syntax introduces certain parsing difficulties.

So you can use the keyword as for this:

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

The as operator is available in both .ts and .tsx files, and is identical in behavior to the other type assertion style.

1 Comment

This does not work in my case, I'm updating the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.