Avatar ·

TypeScript中“Could not find a declaration file for module”错误——如何修复?

你好!我是一名TypeScript初学者,在导入第三方模块时遇到了问题。我有一个用TypeScript编写的简单Express.js项目。我通过npm安装了`lodash`包,但当我尝试在我的`index.ts`文件中导入它时,编译器报错了。 这是我的代码: ```typescript import _ from 'lodash'; const arr = [1, 2, 3, 4, 5]; const shuffled = _.shuffle(arr); console.log(shuffled); ``` 运行`tsc`时,我得到: ``` Could not find a declaration file for module 'lodash'. '/path/to/node_modules/lodash/lodash.js' implicitly has an 'any' type. Try `npm i --save-dev @types/lodash` if it exists or add a new declaration (.d.ts) file containing `declare module 'lodash';` ``` 我理解TypeScript需要第三方模块的声明文件(`.d.ts`),但不太明白这是如何工作的。为什么有些模块无需额外操作就能工作,而有些则不行?以及“implicitly has an 'any' type”是什么意思?