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

如何解决VSCode中TypeScript的"Type annotations can only be used..."错误

解决"Type annotations can only be used in TypeScript files.ts(8010)"错误

以下是几个无需禁用TypeScript验证的有效解决方案,按优先级尝试:

  • 检查VS Code文件关联配置
    有时候VS Code会错误地将.ts文件识别为JavaScript,导致语法校验异常。打开VS Code设置(Ctrl+, / Cmd+,),搜索files.associations,确保.ts关联的是typescript。可以直接在settings.json中添加或修改:

    "files.associations": {
        "*.ts": "typescript",
        "*.tsx": "typescriptreact"
    }
    
  • 验证tsconfig.json配置有效性
    确保项目根目录的tsconfig.json配置正确,且被VS Code正常识别:

    • 检查include字段是否覆盖了所有你的.ts/.tsx文件,比如:
      "include": ["src/**/*"],
      "exclude": ["node_modules", "dist"]
      
    • 确认compilerOptions中的jsx配置与React项目匹配(仅React项目需要),比如:
      "compilerOptions": {
        "jsx": "react-jsx"
      }
      
    • 如果是monorepo结构,检查子项目的tsconfig.json是否继承了根目录的基础配置,避免路径或规则冲突。
  • 修复ESLint配置冲突
    ESLint与TypeScript解析器不匹配也会导致这类错误:

    • 确保ESLint使用@typescript-eslint/parser作为解析器,在.eslintrc.js(或对应的配置文件)中设置:
      module.exports = {
        parser: '@typescript-eslint/parser',
        parserOptions: {
          project: './tsconfig.json',
          tsconfigRootDir: __dirname,
        },
        plugins: ['@typescript-eslint'],
        extends: [
          'eslint:recommended',
          'plugin:@typescript-eslint/recommended',
          'plugin:@typescript-eslint/recommended-requiring-type-checking'
        ],
        // 其他规则配置...
      };
      
    • 确认@typescript-eslint/eslint-plugin和@typescript-eslint/parser的版本与项目中TypeScript版本兼容,版本差异过大可能引发解析错误。
  • 重启TypeScript语言服务
    VS Code的TypeScript服务偶尔会出现缓存异常,导致错误识别。打开命令面板(Ctrl+Shift+P / Cmd+Shift+P),输入TypeScript: Restart TS Server并执行,多数情况下能临时解决这类偶发错误。

  • 检查文件扩展名与语法匹配
    在React项目中,如果.ts文件包含JSX语法,必须将扩展名改为.tsx,否则VS Code会无法正确识别TypeScript-JSX语法,引发校验错误。同时确保tsconfig.json中的jsx配置正确。

  • 切换到项目本地TypeScript版本
    VS Code默认可能使用全局TypeScript版本,与项目依赖的版本不一致会导致校验错误。打开命令面板,输入TypeScript: Select TypeScript Version,选择Use Workspace Version,使用项目node_modules中的TypeScript版本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 07:25:18