[TOC]

typescript常见问题解决

1. 规则校验类报错

1.1 Cannot find module './img/one.png' or its corresponding type declarations.

在vue3项目中, 使用import引入图片资源的时候,报如图所示的错误,经过确认,引用路径没有问题。

1.1.1 报错原因

在 TypeScript 项目中通过 import 导入图片时出现 Cannot find module 错误,通常是由于 TypeScript 无法识别非代码资源(如 .png.jpg 等文件)导致的。

1.1.2 解决方案

1.1.2.1 添加类型声明文件(实测有效)

在项目的src目录中创建或修改images.d.ts,声明图片模块类型:

// 示例:src/images.d.ts
declare module '*.png' {
  const value: string;
  export default value;
}
declare module '*.jpg' {
  const value: string;
  export default value;
}
// 可扩展其他图片格式(如 .svg、.jpeg、.gif、.bmp、.tif/.tiff、.webp 等)
1.1.2.2 确保声明文件被 TypeScript 识别

检查 tsconfig.json‌:确保声明文件路径包含在 includetypeRoots 配置中:

{
  "compilerOptions": {
    "typeRoots": ["./node_modules/@types", "./src/types"]
  },
  "include": ["src/**/*"]
}
1.1.2.3 验证导入路径
  • 确认图片路径正确且文件存在35。

  • 若使用别名(如 @/assets),需在 tsconfig.json 中配置 paths

    {
      "compilerOptions": {
        "baseUrl": ".",
        "paths": {
          "@/*": ["src/*"]
        }
      }
    }
    
1.1.2.4 替代方案(非推荐)
  • 使用 require‌:动态导入图片(需配置 Webpack 或 Vite 支持):

    const imgPath = require('./assets/image.png') as string;
    
  • 直接使用 URL‌:将图片放在 public 目录并通过绝对路径引用。

2. 在vue中使用TS报错

2.1 JSON.parse()解析路由中的query参数类型报错

1、报错原因

Vue3 + Vue Router 4 + TypeScript 中,router.currentRoute.value.query 的类型是 LocationQuery,而不是字符串:

type LocationQuery = Record<string, string | string[]>;

JSON.parse() 只接受 string 类型,所以会报错:

Argument of type 'LocationQuery' is not assignable to parameter of type 'string'

2、解决方法

2.1 先取具体字段,并显式转成 string:假设你的路由是 /page?data={"a":1},并要解析 data 字段:

import { useRoute } from 'vue-router';
const route = useRoute();
const rawData = route.query.data;  // 类型: string | string[] | undefined
const parsed = rawData ? JSON.parse(String(rawData)) : null;
console.log(parsed);

2.2 给 JSON 数据提前 encodeURIComponent,避免特殊字符问题

// 传递参数
router.push({ path: '/page', query: { data: encodeURIComponent(JSON.stringify(obj)) } });

// 获取参数
const rawData = route.query.data;
const parsed = rawData 
    ? JSON.parse(decodeURIComponent(String(rawData))) 
    : null;

2.3 给返回值声明类型(推荐):TypeScript 可以自动推断解析后的数据类型:

interface MyData {
  a: number;
  b?: string;
}

const rawData = route.query.data;
const parsed: MyData | null = rawData 
    ? JSON.parse(String(rawData)) 
    : null;
Last Updated: 7/24/2025, 4:42:46 PM