工作期间,使用ts编译代码的过程经常有报错提示,该篇文章收集下自己在工作过程中遇到的ts报错合集,以及对应的解决方法,不定期更新。
1. Cannot find module 'undici-types'. Did you mean to set the 'moduleResolution' option to 'nodenext',
参考文章:chengpeiquan.com/article/typ… 【分析的原因【很专业】并提出了解决办法】
使用配置:skipLibCheck 【通知 TypeScript 跳过这些依赖库的类型检查(扩展名为 .d.ts 的文件),从而只检查开发者编写的源代码。】
2. vscode 提示【Cannot find module ‘vue’. Did you mean to set the ‘moduleResolution’ option to ‘node’
解决:使用配置:moduleResolution 【模块解析作用】
3. Argument of type 'xx’ is not assignable to parameter of type 'xxx‘
类型赋值错误【一般转成any可以解决】
4.Cannot redeclare block-scoped variable 'console'
参考链接:www.jianshu.com/p/78268bd9a…
原因:在默认状态下,typescript 将 DOM typings 作为全局的运行环境,所以当我们声明 name时, 与 DOM 中的全局 window 对象下的 name 属性出现了重名。因此,报了 error TS2451: Cannot redeclare block-scoped variable 'name'. 错误
解决:
既然与全局的变量出现重名,那我们将脚本封装到模块(module)内。module 有自己的作用域,自然不会与全局作用域的变量产生冲突。
在 Typescript 中,只要文件存在 import 或 export 关键字,都被视为 module
const name = 'youthcity';
function greeter(name:string) { return `Hello ${name}`; }
console.log(greeter(name));
export {};
在脚本的最后一行,添加了 export {};。将文件声明为 module, 变量 name 被限制在了 module 的作用域下,因此不会与全局的name产生冲突。