我似乎无法访问道具形状
https://cdn.discordapp.com/attachments/508357248330760249/831773180162998292/Untitled.png
答案 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。