首页 > 解决方案 > 如何使用打字稿渲染条件道具并做出反应?

问题描述

我似乎无法访问道具形状

https://cdn.discordapp.com/attachments/508357248330760249/831773180162998292/Untitled.png

标签: reactjstypescript

解决方案


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


推荐阅读