What is the correct return type replacement for JSX.Element when the global JSX namespace is deprecated?
P粉404539732
P粉404539732 2023-10-26 21:00:38
0
2
773

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粉404539732
P粉404539732

reply all(2)
P粉465287592

Use React.JSX.


Or import JSX from "react":

import {JSX} from 'react'
P粉521748211

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template