如何将父级 prop 类型检查传播给子级

问题描述 投票:0回答:1

我有一个条件组件,仅在满足条件时才呈现应用程序的其他部分。在某些情况下,我可能需要将条件渲染组件使用的变量传递给某些父组件子组件,但 TypeScript 不知道这一点,并且会报错。

这是一些代码:

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)

这里的事情是,我已经检查过

X
存在于
conditionalRender
父组件
... condition={!!x}>

我很想找到一种方法来告诉 TS

X
属性已经被检查并且它不是未定义的,因为目前,对于上面的示例,我必须在
ConditionalRender
组件中执行类似的操作:

{!!x && <A x={x} />}

reactjs typescript
1个回答
0
投票

您应该将

x
参数从
ConditionalRender
传递到
A
组件,而不是从
B
传递,其中
x
可以是
undefined

type ConditionalRenderProps<T> = {
  params: T
  render: (x: NonNullable<T | null | undefined>) => ReactElement
}

const ConditionalRender = <T,>({ render, params }: ConditionalRenderProps<T>): ReactElement => {
  if (params === undefined || params === null) {
    return <></>
  }
  return <div>{render(params)}</div>
}



type AProps = {
  x: string
}
const A: FC<AProps> = ({ x }) => {
  return <>{x}</>
}

const B = (): ReactElement => {
  let x: string | undefined = "Hello"

  return (
    <ConditionalRender
      params={x}
      render={(x) => {
        return <A x={x} />
      }}
    />
  )
}
© www.soinside.com 2019 - 2024. All rights reserved.