search

Home  >  Q&A  >  body text

What is the correct return type replacement for JSX.Element when the global JSX namespace is deprecated?

In @types/react, the global JSX namespace has been deprecated:

declare global {
    /**
     * @deprecated Use `React.JSX` instead of the global `JSX` namespace.
     */
    namespace JSX {
    ...
    }
}

Since I enabled ESLint's deprecation/deprecation rules (from the plugin eslint-plugin-deprecation), I now receive an error for function component return type like this:

export default function TestComponent(): JSX.Element { // This JSX is marked as deprecated
    return (
        <span>Test</span>
    );
}

Now that the global JSX namespace has been deprecated, what is the correct return type replacement for JSX.Element in this case?

Is it React.JSX.Element as stated in the deprecation message:

export default function TestComponent(): React.JSX.Element { ... }

Or ReactElement like this:

import { ReactElement } from "react";
export default function TestComponent(): ReactElement { ... }

Or better yet, declare the function component using React.FC and let TypeScript infer the return type, like this:

export const TestComponent: React.FC = () => { ... };


P粉404539732P粉404539732437 days ago801

reply all(2)I'll reply

  • P粉465287592

    P粉4652875922023-10-27 11:55:24

    Use React.JSX.


    Or import JSX from "react":

    import {JSX} from 'react'
    

    reply
    0
  • P粉521748211

    P粉5217482112023-10-27 00:02:44

    Use React.ReactElement directly (or more accurately, React.ReactElement | null):

    import { ReactElement } from "react";
    
    export function TestComponent(): ReactElement | null {
      return (
        Math.random() < 0.5
          ? null
          : <>
              A single Element (could be a Fragment like here)
            </>
      );
    }

    This is exactly what (no longer recommended) React.FC Enforcement:

    interface FunctionComponent<P = {}> {
      (props: P, context?: any): ReactElement<any, any> | null;
      // ...
    }

    It is also JSXElementConstructor:

    type JSXElementConstructor<P> =
      | ((props: P) => ReactElement<any, any> | null) // Case of a Function Component
      | (new (props: P) => Component<any, any>); // Case of a Class-based Component

    That being said, unless you have some rules that force you to enter a function component return type, you can ignore it for the sake of simplicity:

    export function TestComponent() {
      // ...
    }

    Apparently the function can now return anything, Typescript won't complain...unless you try to use it as a functional component in a JSX template, which is the case in fb/cra#8177:

    const Example = () => <Component />; // Error here, due to Component returning the wrong thing

    reply
    0
  • Cancelreply