javascript - 使用默认值解构空对象时 typescript 类型错误?

标签 javascript reactjs typescript ecmascript-6

我正在使用 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/

相关文章:

为什么有些API在返回的JSON数据头部加一个while(1);

javascript - 计算对象中同一键内的多个唯一值

JavaScript - 使用数组索引转换为字符串

javascript - 使用 d3 动画条形图并使用react

javascript - Angular 2 : Validate child component form fields from the parent component

javascript - 为什么 'o'是真的? JavaScript( Angular )

javascript - 重定向(react router dom)给 Expected 一个赋值或函数调用,而是看到一个表达式 no-unused-expressions

java - Spring 应用程序中通过 ReactJS REST 生成的文件列表为空

sql-server - TypeORM 处理数据库中断

typescript - 可视代码类型脚本在空格和 tslint 上显示错误