如何使用打字稿渲染条件道具并做出反应?

时间:2021-04-14 06:18:47

标签: reactjs typescript

1 个答案:

答案 0 :(得分:2)

TypeScript 引发该错误,因为该属性仅针对 shape: 'circle' 定义,因此您必须通过匹配标签来缩小其类型,在本例中为 shape 属性。

示例:

type ButtonProps = { fullName: string } & (
  | { shape: 'circle'; radius: number }
  | { shape: 'square'; width: number }
)
declare const props: ButtonProps

props.radius // Property 'radius' does not exist on type 'ButtonProps'

if (props.shape === 'circle') {
  props.radius // number
}

https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions