我有一个条件组件,它仅在满足条件时才呈现应用程序的其他部分.在某些情况下,我可能需要将条件呈现组件使用的变量传递给这个父组件的一些子组件,但TypeScrip不知道这一点,它会报告一个错误.
以下是一些代码:
type AProps = {
x: string
}
const A: FC<AProps> = ({x}) => {return (<>{x}</>)}
const B = () => {
let x: string | undefined
return (
<ConditionalRender condition={!!x}>
<A x={x} />
</ConditionalRender>
)
}
使用这个代码片段,我有一个关于x={X}
的TS错误
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.ts(2322)
这里的问题是,我已经判断了conditionalRender
父组件... condition={!!x}>
上存在X
我很想找到一种方法来告诉TS,X
prop已经被判断过了,它不是未定义的,因为目前,在上面的例子中,我必须在ConditionalRender
组件中做这样的事情:
{!!x && <A x={x} />}