【发布时间】:2019-02-06 17:02:49
【问题描述】:
我正在用 ReactJS + Typescript 编写一个 Web 应用程序。我有一个如下定义的功能组件。
我的问题如下:在 props 中,对于属性 exercise,父组件正在传递一个对象,要么初始化为空,要么具有我指定的特定类型 Exercise。然后 Typescript 引发以下错误:
[ts] Property 'description' does not exist on type '{} | Exercise'[ts] Property 'title' does not exist on type '{} | Exercise'
我如何重构它,以便如果对象确实为空,它将使用默认值,否则使用传递的值?
编辑:添加了我使用的其他道具
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>
)
【问题讨论】:
标签: javascript reactjs typescript ecmascript-6