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

如何解决TypeScript中‘Type 'undefined' is not assignable to type 'BlobPart'’错误

解决TypeScript类型错误:'Blob | null | undefined' 无法赋值给 'BlobPart'

错误原因

getCroppedImg的返回值可能是null或undefined,但new File()的第一个参数要求是有效的BlobPart类型(不能包含空值),TypeScript的严格类型检查会拦截这种潜在的无效值传入,因此抛出类型错误。

修改方案

在使用croppedImage创建File实例前,先判断它是否为有效的Blob对象,排除null和undefined的情况:

修改后的代码

const showCroppedImage = useCallback(async () => {
  try {
    const croppedImage = await getCroppedImg(inputImg, croppedAreaPixels);
    // 校验croppedImage是否为合法Blob实例
    if (croppedImage instanceof Blob) {
      onCropImage(
        new File([croppedImage], imgName, {
          type: "image/png",
          lastModified: new Date().getTime(),
        })
      );
    } else {
      // 处理裁剪失败的场景,可根据需求调整逻辑
      console.error("裁剪未生成有效图片Blob");
    }
  } catch (e) {
    console.error(e);
  }
}, [inputImg, croppedAreaPixels, imgName, onCropImage]);

补充说明

  • 不要用if (croppedImage)这种简单判断,因为空Blob实例在布尔判断中会被视为false,导致误判有效裁剪结果
  • 如果getCroppedImg的类型定义不明确,可手动补充返回值类型约束,示例:
    // 假设这是自定义的getCroppedImg函数,明确返回值类型
    async function getCroppedImg(img: HTMLImageElement, area: CroppedArea): Promise<Blob | null> {
      // 函数实现逻辑
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 17:53:11