我正在使用 ReactJS + Typescript 编写一个 Web 应用程序。我有一个定义如下的功能组件。
我的问题如下:在 Prop 中,对于属性exercise
,父组件正在传递一个对象,该对象要么初始化为空,要么是我指定的某种类型, 锻炼
。然后 Typescript 会引发以下错误:
[ts] 类型“{} | 上不存在属性“描述”练习'
[ts] 类型“{} | 上不存在属性“标题”练习'
如何重构它,以便如果对象确实为空,它将使用默认值,否则使用传递的值?
编辑:添加了我使用的其他 Prop
type Exercise = {
description: string
id: string
muscles: string
title: string
}
type Props = {
category: string
children?: never
exercise: {} | Exercise
exercises: Array<[string, Exercise[]]>
onSelect: (id: string) => void
}
const Exercises = ({
exercises,
category,
onSelect,
exercise: {
description = 'Please select an exercise',
title = 'Welcome!'
}
}: Props) => (
<Grid container>
<Grid item sm>
{/* Some stuff going on with exercises, category and onSelect */ }
</Grid>
<Grid item sm>
<Paper>
<Typography variant="h4">{title}</Typography>
<Typography variant="subtitle1">{description}</Typography>
</Paper>
</Grid>
</Grid>
)
最佳答案
我认为类似的东西应该有效
type Exercise = {
description: string
id: string
muscles: string
title: string
}
type Props = {
exercise: Partial<Exercise>
}
const Exercises = (props: Props) => {
const exercice = {
description:'Please select an exercise',
title: 'Welcome!',
...props.exercise
}
return (
<Grid container>
<Grid item sm>
<Paper>
<Typography variant="h4">{exercice.title}</Typography>
<Typography variant="subtitle1">{exercice.description}</Typography>
</Paper>
</Grid>
</Grid>
)
}
编辑:对齐代码
关于javascript - 使用默认值解构空对象时 typescript 类型错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54558884/