【发布时间】:2021-02-01 15:18:22
【问题描述】:
我正在尝试创建一个接受 2 个参数的函数:一个 React Functional 组件和它的 props 对象,并且具有以下要求:
- 当没有组件需要的道具时,该函数应该能够只接受一个参数
- 当组件的 props 丢失或与相应类型不匹配时,Typescript 应该报错
`
import React, { PropsWithChildren, FC, FunctionComponent } from 'react';
function render<T> (
Component: FC<PropsWithChildren<T>>,
props = {} as PropsWithChildren<PropsWithChildren<T>>,
): JSX.Element {
return <Component { ...props }>{ props?.children }</Component>;
}
interface FooProps { name: string; }
const Foo = ({ name }: FooProps): JSX.Element => <p>{name}</p>;
const Bar = (): JSX.Element => <p>bar</p>;
// Incorrect
render(Foo, { name: 'asdd', a: '' }); // Passing. Expected to fail because prop 'a' is not expected
render(Foo); // Passing. Expected to fail because the component's prop 'name' is missing
render(Bar, { name: 'test' }); // Passing. Expected to fail, because Bar's props object is incorrect
// Correct
render(Foo, {}); // Failing. Expected to fail because prop 'name' is required
render(Foo, { name: 'asdd' }); // Passing. Expected to pass with correct props
render(Bar); // Passing. Expected to pass because Bar does not require any props
render(Bar, {}); // Passing. Expected to pass because Bar does not require any props
`
使用当前版本的代码,我能够满足大部分要求,但以下要求除外:
- Typescript 在需要时应该需要 props 对象
- Typescript 不应允许传递组件不需要的道具
不知道我做错了什么。任何建议将不胜感激。
【问题讨论】:
标签: javascript reactjs typescript