我应该为对象休息道具声明什么类型



以下是react router中关于如何为受保护的路由添加组件的示例:

function PrivateRoute({ component: Component, ...rest }) {
return (
<Route
{...rest}
render={props =>
fakeAuth.isAuthenticated ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: "/login",
state: { from: props.location }
}}
/>
)
}
/>
);
}

https://reacttraining.com/react-router/web/example/auth-workflow

我试着在我的Typescript项目中实现这个功能,灵感来自上面的例子。

import * as React from 'react';
import {
Route,
Redirect,
} from 'react-router-dom';
interface PrivateRouteProps {
component: React.Component; // passed as prop
isSignedIn: boolean; // injected as prop by redux
location: Location;
}
const PrivateRoute = (props: PrivateRouteProps) => {
const { component: Component, isSignedIn, location } = props;
return (
<Route
{...rest}
render={(routeProps) =>
isSignedIn ? (
<Component {...routeProps} />
) : (
<Redirect
to={{
pathname: '/signin',
state: { from: location }
}}
/>
)
}
/>
);
};
export default PrivateRoute;

我得到以下错误

[ts] Cannot find name 'rest'.
any
[ts] JSX element type 'Component' does not have any construct or call signatures.
const Component: React.Component<{}, {}, any>

1(您还没有从析构函数操作符中提取剩余的道具,要获得其余的道具,您需要这个:

const { component: Component, isSignedIn, location, ...rest } = props;

2(Component不是您所认为的,它是一个类元素构造的接口,但您正在使用它来定义类型。如果您希望将其强制作为元素,则需要使用JSX.Element

最终你应该留下:

import * as React from 'react';
import {
Route,
Redirect,
} from 'react-router-dom';
interface PrivateRouteProps {
component: JSX.Element; // passed as prop
isSignedIn: boolean; // injected as prop by redux
location: Location;
}
const PrivateRoute = (props: PrivateRouteProps) => {
const { component, isSignedIn, location, ...rest } = props;
return (
<Route
{...rest}
render={(routeProps) =>
isSignedIn ? (
<Component {...routeProps} />
) : (
<Redirect
to={{
pathname: '/signin',
state: { from: location }
}}
/>
)
}
/>
);
};
export default PrivateRoute;
import React, { forwardRef, ReactNode } from "react"
interface ICardProps {
children: ReactNode;
className?: string;
[props: string]: any;
}
const Card = forwardRef<HTMLDivElement, ICardProps>(( props, ref ) => {
const { className, children, ...rest } = props;
return <div ref={ref} className={className} {...rest}>{children}</div>
})
export default Card;

一个简单的解决方案可以是:

interface PrivateRouteProps {
component: React.Component; // passed as prop
isSignedIn: boolean; // injected as prop by redux
location: Location;
// Here prop is a key with type string and value type could be any
[props: string]: any;
}