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

如何解决TypeScript中image类型为unknown的错误

解决TypeScript中image类型为unknown的错误

你的问题核心是createImage函数返回的Promise没有指定类型,TypeScript默认推断为Promise<unknown>,所以await createImage(imageSrc)得到的image就是unknown类型,无法直接访问它的width、height等属性。下面是具体的修改步骤和完整代码:

关键修改点

  • 给createImage函数指定返回类型Promise<HTMLImageElement>,明确resolve的是图片元素实例
  • 替换所有any类型为具体类型,让代码类型更安全
  • 修复drawImage调用时的语法错误(参数之间缺少逗号)
  • 给最终返回的Promise指定类型Promise<Blob | null>

修改后的完整代码

// 指定返回类型为Promise<HTMLImageElement>
const createImage = (url: string): Promise<HTMLImageElement> =>
  new Promise((resolve, reject) => {
    const image = new Image();
    image.addEventListener("load", () => resolve(image));
    image.addEventListener("error", error => reject(error));
    image.setAttribute("crossOrigin", "anonymous");
    image.src = url;
  });

// 参数改为number类型
function getRadianAngle(degreeValue: number) {
  return (degreeValue * Math.PI) / 180;
}

// 定义pixelCrop的接口,明确结构
interface PixelCrop {
  x: number;
  y: number;
  width: number;
  height: number;
}

// 指定参数类型和返回类型
export default async function getCroppedImg(
  imageSrc: string,
  pixelCrop: PixelCrop,
  rotation = 0
): Promise<Blob | null> {
  // 现在image的类型是HTMLImageElement,不再是unknown
  const image = await createImage(imageSrc);
  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");
  if (!ctx) {
    return null;
  }

  const maxSize = Math.max(image.width, image.height);
  const safeArea = 2 * ((maxSize / 2) * Math.sqrt(2));

  canvas.width = safeArea;
  canvas.height = safeArea;

  ctx.translate(safeArea / 2, safeArea / 2);
  ctx.rotate(getRadianAngle(rotation));
  ctx.translate(-safeArea / 2, -safeArea / 2);

  ctx.fillStyle = "#DCDCDC";
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  // 修复这里的逗号缺失
  ctx.drawImage(
    image,
    safeArea / 2 - image.width * 0.5,
    safeArea / 2 - image.height * 0.5
  );
  const data = ctx.getImageData(0, 0, safeArea, safeArea);

  canvas.width = pixelCrop.width;
  canvas.height = pixelCrop.height;

  ctx.putImageData(
    data,
    Math.round(0 - safeArea / 2 + image.width * 0.5 - pixelCrop.x),
    Math.round(0 - safeArea / 2 + image.height * 0.5 - pixelCrop.y)
  );

  // 指定返回Promise的类型
  return new Promise<Blob | null>(resolve => {
    canvas.toBlob(file => {
      resolve(file);
    }, "image/png");
  });
}

内容的提问来源于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:40:27