You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript报错:Property does not exist on type问题求助

解决TypeScript解构可选对象的类型错误

错误原因

你定义的reminderInfo是可选属性(类型后带?),所以它的实际类型是{ reminderButtonText?: string; reminderUrl?: string } | undefined。直接解构undefined会报错,因为undefined不存在reminderUrl属性。

几种可行的解决方法:

  • 给reminderInfo设置默认空对象
    在组件接收参数时,给reminderInfo默认赋值为空对象,确保它永远不会是undefined,解构操作就不会触发类型错误:

    type Props = {
      reminderInfo?: {
        reminderButtonText?: string;
        reminderUrl?: string;
      };
    };
    const component: FunctionComponent<Props> = ({
      reminderInfo = {}, // 设置默认空对象
    }) => {
      const onPress = () => {
        const { reminderUrl } = reminderInfo; // 正常解构无错误
      };
    };
    
  • 解构前先判断reminderInfo是否存在
    在onPress函数内先检查reminderInfo的有效性,再执行解构:

    const onPress = () => {
      if (!reminderInfo) return; // 不存在则直接返回,避免后续错误
      const { reminderUrl } = reminderInfo;
      // 此处可安全使用reminderUrl
    };
    

    也可以用可选链直接取值,省去解构步骤:

    const onPress = () => {
      const reminderUrl = reminderInfo?.reminderUrl;
      // reminderUrl类型为string | undefined,符合原定义
    };
    
  • 非空断言(谨慎使用)
    如果你能百分百确定reminderInfo在调用onPress时一定存在,可以用非空断言!告诉TypeScript该值不会是undefined:

    const onPress = () => {
      const { reminderUrl } = reminderInfo!;
    };
    

    注意:如果实际运行时reminderInfo为undefined,这种写法会触发运行时错误,仅在确定值存在时使用。

内容的提问来源于stack exchange,提问作者Bomber

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 14:53:18