【发布时间】:2021-03-22 00:14:43
【问题描述】:
我正在使用 TypeScript 构建一个 React 应用程序。我有一个RequiresPermission 组件,它基于谓词,应该呈现一个或另一个组件并转发所有道具。
type Props = {
NotPermittedComponent: React.ComponentType;
PermittedComponent: React.ComponentType;
isPermitted: boolean;
};
const RequiresPermisson = ({
NotPermittedComponent,
PermittedComponent,
isPermitted,
...rest
}: Props) =>
isPermitted ? (
<PermittedComponent {...rest} />
) : (
<NotPermittedComponent {...rest} />
);
export default RequiresPermisson;
当我渲染组件时,TypeScript 大喊RequiresPermission in:
const PERMITTED_TEXT = 'permitted';
const NOT_PERMITTED_TEXT = 'not-permitted';
type TestPropsProps = {
text: string;
};
const NotPermittedTestComponent: React.FunctionComponent<TestPropsProps> = ({
text,
}) => (
<div>
<span>{NOT_PERMITTED_TEXT}</span>
{text}
</div>
);
const PermittedTestComponent: React.FunctionComponent<TestPropsProps> = ({
text,
}) => (
<div>
<span>{PERMITTED_TEXT}</span>
{text}
</div>
);
const createProps = ({
NotPermittedComponent = NotPermittedTestComponent,
PermittedComponent = PermittedTestComponent,
isPermitted = false,
text = 'foo',
} = {}) => ({
NotPermittedComponent,
PermittedComponent,
isPermitted,
text,
});
const props = createProps();
render(<RequiresPermission {...props} />);
说:
Type '{ NotPermittedComponent: FunctionComponent<TestPropsProps>; PermittedComponent: FunctionComponent<TestPropsProps>; isPermitted: boolean; text: string; }' is not assignable to type '{ NotPermittedComponent: ComponentType<{}>; PermittedComponent: ComponentType<{}>; isPermitted: boolean; }'.
Types of property 'NotPermittedComponent' are incompatible.
Type 'FunctionComponent<TestPropsProps>' is not assignable to type 'ComponentType<{}>'.
Type 'FunctionComponent<TestPropsProps>' is not assignable to type 'FunctionComponent<{}>'.
Types of parameters 'props' and 'props' are incompatible.
Type '{ children?: ReactNode; }' is not assignable to type 'PropsWithChildren<TestPropsProps>'.
Property 'text' is missing in type '{ children?: ReactNode; }' but required in type 'TestPropsProps'.
我也尝试将Record<string, unknown> 用作props,但这也不起作用。
您如何解决此问题以传递道具或允许任何(不是any 类型)道具,以便...rest 参数起作用?
【问题讨论】:
-
“允许任何道具” -
(props: any) => ...?unknown作为 return 类型比作为参数类型更有意义。 -
由于您不接受任何答案,我会假设缺少某些内容。您能否就您的问题的哪些部分没有得到回答或为什么它不适合您的用例提供任何反馈?
标签: reactjs typescript typescript-typings react-typescript