我有一个TypeScript函数,该函数在被调用时会根据提供的参数有条件地返回react-router-dom
路由。但是,当我声明返回类型为(Route | null)
时,出现以下错误:
TS2740:类型“元素”缺少类型的以下属性 'Route':上下文,setState,forceUpdate,render和2 更多。
我没有正确声明此函数的返回类型,如果是,应该是什么?我也尝试过(Route<RouteProps> | null)
,但这似乎并不能解决问题。谢谢。
import * as React from 'react';
import { Route } from 'react-router-dom';
const SampleComponent: React.FC = () => <h1>hello world</h1>;
export const getRoute = (returnRoute: boolean): (Route | null) => {
if (returnRoute) {
return (
<Route
component={SampleComponent}
exact
path="/samplePath"
/>
);
}
return null;
};
答案 0 :(得分:1)
如果您查看Route
的签名。
export class Route<T extends RouteProps = RouteProps> extends React.Component<T, any> { }
您会看到它只是一堂课。在您的回报中,您是在说要返回该类的一个实例(即new Route(props)
或null
,而不是该类的一个组成部分(一个ReactNode
)。就像您要返回一个React.Component
React.ReactNode基本上是React组件的一组有效返回值:
type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;
因此,为回答您的问题,您可以将(Route | null)
替换为React.ReactNode
。