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

React useCallback中res可能为undefined的TypeScript报错修复咨询

修复TypeScript中'res' is possibly 'undefined'错误

有几种实用的修复方式:

方案1:用常量锁定非undefined状态

TypeScript没办法在setFileList的回调闭包里跟踪到res的类型收窄,你可以在if判断后把res赋值给一个块级常量,让TypeScript确认它不会是undefined:

const handleFileDescription = React.useCallback(
  (idToEdit: number, desc: string) => {
    var res = linq.from(fileList).firstOrDefault((t) => t.id === idToEdit);
    if (res !== undefined) {
      const safeRes = res;
      setFileList((prevState) => {
        return [
          ...prevState.filter((t) => t.id !== idToEdit),
          {
            ...safeRes,
            desc: desc,
            id: idToEdit,
            file: safeRes.file,
          },
        ];
      });
    }
  },
  [fileList, attachmentCount]
);

也可以直接用非空断言res!替代safeRes,但要确保你能100%保证此时res不会是undefined。

方案2:基于prevState直接操作(更推荐)

既然setFileList的回调能拿到最新的状态,直接在回调里查找目标项,完全避开外部res的类型问题,还能减少依赖项优化性能:

const handleFileDescription = React.useCallback(
  (idToEdit: number, desc: string) => {
    setFileList((prevState) => {
      const targetItem = prevState.find((t) => t.id === idToEdit);
      if (!targetItem) return prevState;
      
      return [
        ...prevState.filter((t) => t.id !== idToEdit),
        {
          ...targetItem,
          desc: desc,
          id: idToEdit,
          file: targetItem.file,
        },
      ];
    });
  },
  [attachmentCount]
);

这种写法更符合React状态更新的最佳实践,不用依赖外部的fileList,避免了闭包捕获旧状态的问题。

方案3:自定义类型守卫(适合复用场景)

如果需要多次判断值是否为undefined,可以写一个类型守卫函数,让TypeScript更明确类型:

function isDefined<T>(value: T | undefined): value is T {
  return value !== undefined;
}

const handleFileDescription = React.useCallback(
  (idToEdit: number, desc: string) => {
    var res = linq.from(fileList).firstOrDefault((t) => t.id === idToEdit);
    if (isDefined(res)) {
      setFileList((prevState) => {
        return [
          ...prevState.filter((t) => t.id !== idToEdit),
          {
            ...res,
            desc: desc,
            id: idToEdit,
            file: res.file,
          },
        ];
      });
    }
  },
  [fileList, attachmentCount]
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 20:05:03