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

ESLint对DOM类型误报`Unsafe assignment of an any value`问题排查

Next.js Canvas组件ESLint误报Unsafe assignment of an any value问题解决

问题背景

用最新版create-next-app搭建的Next.js项目,编写Canvas组件时碰到个棘手问题:ESLint在VSCode编辑器和终端运行时,都给const context = canvasRef.current?.getContext("2d");这行报Unsafe assignment of an any value错误,但TypeScript明明能正确识别context是CanvasRenderingContext2D | null类型。试过重启VSCode、重启ESLint服务、给ESLint添加browser环境这些操作,都没解决,而且只有DOM相关类型会出现这种误报。

组件代码

import { useEffect, useRef } from "react";

export function Canvas() {
  const canvasRef = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    const context = canvasRef.current?.getContext("2d");

    if (!context || !(context instanceof CanvasRenderingContext2D)) {
      return;
    }

    context.fillRect(0, 0, 100, 100);
  }, []);

  return (
    <canvas ref={canvasRef} width={600} height={600}>
      test
    </canvas>
  );
}

项目配置

tsconfig.json

{
  "compilerOptions": {
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "paths": {
      "@/*": ["./src/*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"],
  "references": []
}

.eslintrc.json

{
  "extends": "next/core-web-vitals",
  "rules": {
    "@typescript-eslint/no-misused-promises": "off"
  }
}

可行解决方案

1. 给context显式添加类型注解

直接给变量指定明确类型,让ESLint能清晰识别,避免误判为any:

const context: CanvasRenderingContext2D | null = canvasRef.current?.getContext("2d");

2. 针对性调整ESLint规则

如果不想逐个场景添加类型注解,可以通过配置ESLint规则或单行注释解决:

全局规则调整

修改.eslintrc.json,给@typescript-eslint/no-unsafe-assignment规则添加适配配置:

{
  "extends": "next/core-web-vitals",
  "rules": {
    "@typescript-eslint/no-misused-promises": "off",
    "@typescript-eslint/no-unsafe-assignment": [
      "error",
      {
        "ignorePropertyInitializations": true
      }
    ]
  }
}

单行车忽略

在报错行上方添加注释,仅忽略该行的误报:

// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const context = canvasRef.current?.getContext("2d");

3. 更新相关依赖包

这类误报有时是因为@typescript-eslint插件、TypeScript版本不兼容导致的,尝试更新依赖到最新版:

npm update typescript @typescript-eslint/eslint-plugin @typescript-eslint/parser

验证方法

修改完成后,重启VSCode或ESLint服务,检查错误是否消失,同时执行npm run lint和npm run build,确保TypeScript编译正常,无其他类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 11:31:11