【问题标题】:Typescript interface on destructed object被破坏对象上的打字稿接口
【发布时间】:2021-11-05 07:18:56
【问题描述】:

我在 React / ts 中销毁的对象出现打字错误。

当我在发布函数中解构 notificationData 时,我收到此错误

“通知”类型上不存在“消息”属性 |未定义'.ts(2339)

我不知道为什么?

【问题讨论】:

  • notificationData? 将该属性标记为可选。因此它可能在那里。因此,您要么需要处理 notificationData 不存在的情况(通过提供后备或预先检查),要么使其成为非可选的(假设它确实总是存在,正如您的代码所期望的那样)。

标签: reactjs typescript


【解决方案1】:

@VLAZ 是正确的。由于消息标记为?,因此您必须处理可能是undefined 的情况。我建议您传递一个与 domain 相同的默认值。

【讨论】:

    【解决方案2】:

    因为notificationData 可能是undefined。所以你应该在使用它之前添加条件

      const {
        url = '',
        notificationData,
      } = props;
    
      const messages = notificationData?.messages;
      const totalunread = notificationData?.totalunread ;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-28
      • 2018-09-15
      • 1970-01-01
      • 2021-07-24
      • 2010-12-25
      • 2018-11-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多