弃用全局 JSX 命名空间后,JSX.Element 的正确返回类型替换是什么?

sce*_*eee 33 jsx typescript reactjs react-typescript

在 中@types/react,全局JSX命名空间已被弃用

declare global {
    /**
     * @deprecated Use `React.JSX` instead of the global `JSX` namespace.
     */
    namespace JSX {
    ...
    }
}
Run Code Online (Sandbox Code Playgroud)

由于我启用了 ESLintdeprecation/deprecation规则(来自 plugin eslint-plugin-deprecation),因此我现在收到函数组件返回类型的错误,如下所示:

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

JSX.Element既然全局命名空间已被弃用,那么在这种情况下,正确的返回类型替换是什么JSX

是否React.JSX.Element如弃用消息中所述:

export default function TestComponent(): React.JSX.Element { ... }
Run Code Online (Sandbox Code Playgroud)

或者是ReactElement这样的:

import { ReactElement } from "react";
export default function TestComponent(): ReactElement { ... }
Run Code Online (Sandbox Code Playgroud)

或者最好使用声明函数组件React.FC并让 TypeScript 推断返回类型,如下所示:

export const TestComponent: React.FC = () => { ... };
Run Code Online (Sandbox Code Playgroud)

ghy*_*ybs 30

直接使用React.ReactElement(或者,更准确地说,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)
        </>
  );
}
Run Code Online (Sandbox Code Playgroud)

这正是(不再推荐)React.FC强制执行的:

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

这也是 a 的定义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
Run Code Online (Sandbox Code Playgroud)

话虽如此,除非您有一些规则强制您输入函数组件返回类型,否则您可以为了方便起见而忽略它:

export function TestComponent() {
  // ...
}
Run Code Online (Sandbox Code Playgroud)

显然,该函数现在可以返回任何内容,并且 TypeScript 不会抱怨......除非您尝试将其用作 JSX 模板中的函数组件,如fb/cra#8177中指出的:

我真正看到的唯一好处React.FC是它指定了返回类型,可以捕获错误[...]

在实践中,我认为这很好,因为一旦你尝试使用它就会被捕获:

const Example = () => <Component />; // Error here, due to Component returning the wrong thing
Run Code Online (Sandbox Code Playgroud)


Mir*_*ili 12

使用React.JSX


JSX从以下位置导入"react"

import type {JSX} from 'react'
Run Code Online (Sandbox Code Playgroud)

  • 我认为这个答案是最直接和正确的,正如文档所说“使用 React.JSX 而不是全局 JSX 命名空间。” (2认同)