直接使用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