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

TypeScript开发图片放大功能出现src不存在等报错如何解决?

报错原因
  • 针对TS2531: Object is possibly 'null'报错:document.querySelector方法在未匹配到对应DOM元素时会返回null,TypeScript的严格空校验规则认为你没有对modalImg、modalTxt做非空判断,不允许直接操作它们的属性。
  • 针对TS2339: Property 'src' does not exist on type 'Element'报错:querySelector默认返回的是通用Element类型,只有HTMLImageElement类型才存在src属性,你没有告诉TypeScriptmodalImg是图片元素,无法识别src属性。
  • 针对TS2322: Type 'string | null' is not assignable to type 'string'报错:getAttribute方法在元素上未找到对应属性时会返回null,但src、innerHTML属性只接受string类型的赋值,null不符合类型要求。
修复方案

你可以通过类型断言、空值处理、非空校验三个方向修改,修复后的代码如下:

const zoom = () => {
  const images = document.querySelectorAll(".voice-details__zoom");
  // 给查询到的元素添加类型断言,明确元素类型
  const modal = document.querySelector(".modal") as HTMLElement | null;
  const modalImg = document.querySelector(".modalImg") as HTMLImageElement | null;
  const modalTxt = document.querySelector(".modalTxt") as HTMLElement | null;
  const close = document.querySelector(".close") as HTMLElement | null;

  images.forEach((image) => {
    image.addEventListener("click", () => {
      // 用空值合并运算符处理getAttribute返回null的情况,默认赋值为空字符串
      const imgSrc = image.getAttribute('data-src') ?? '';
      const imgAlt = image.getAttribute('data-alt') ?? '';
      // 加非空判断,只有元素存在时才操作属性
      if (modalImg) modalImg.src = imgSrc;
      if (modalTxt) modalTxt.innerHTML = imgAlt;
      modal?.classList.add("appear");

      close?.addEventListener("click", () => {
        modal?.classList.remove("appear");
      });
    });
  });
}

如果你的业务逻辑可以100%保证对应元素和属性一定存在,也可以用非空断言符!简化代码,比如modalImg!.src = imgSrc,但更推荐上面的非空判断写法,避免运行时报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 14:12:04