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

2024-05-02

In @types/react,全球JSX名称空间已被弃用 https://github.com/DefinitelyTyped/DefinitelyTyped/blob/266eae5148c535e6b41fe5d0adb2ad23f302bc8a/types/react/index.d.ts#L3182:

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

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

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

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

Is it React.JSX.Element正如弃用消息中所述:

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

或者是ReactElement像这样:

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

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

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

直接使用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)
        </>
  );
}

这正是(不再推荐)React.FC https://github.com/DefinitelyTyped/DefinitelyTyped/blob/266eae5148c535e6b41fe5d0adb2ad23f302bc8a/types/react/index.d.ts#L544-L552强制执行:

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

这也是一个定义JSXElementConstructor https://github.com/DefinitelyTyped/DefinitelyTyped/blob/266eae5148c535e6b41fe5d0adb2ad23f302bc8a/types/react/index.d.ts#L78-L79:

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

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

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

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

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

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

const Example = () => <Component />; // Error here, due to Component returning the wrong thing
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐