我正在尝试使用axios
模拟由nock
发出的请求。过去,此集成存在一些问题,但是in this issue中描述的解决方法有效。当我将Typescript引入混合时,会发生我的问题。尽管axios
随附了用于主库的类型定义文件,但nock
和axios
的集成需要从子目录中导入,如下所示:
import HttpAdapter from 'axios/lib/adapters/http';
Typescript编译器抱怨此行,并显示以下错误:
TS7016: Could not find a declaration file for module 'axios/lib/adapters/http'. 'C:/Users/<user>/<project>/node_modules/axios/lib/adapters/http.js' implicitly has an 'any' type.
Try `npm install @types/axios` if it exists or add a new declaration (.d.ts) file containing `declare module 'axios';`
如何解决此错误?我已经尝试过类似axios
的各种自定义类型定义组合:
// <project>/src/types/axios.d.ts
declare module 'axios/lib/adapters/http` {
import { Adapter } from 'axios';
const HttpAdapter: Adapter;
export default HttpAdapter;
}
我对Typescript不太熟悉,所以我的理论是我的自定义定义文件放置在错误的位置,使用错误的模块名称或未导出正确的内容。任何帮助将不胜感激。
打字稿版本: 2.9.2
tsconfig.json
的(相关)内容:
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"module": "esnext",
"target": "es5",
"lib": ["es2015", "es2017", "dom"],
"moduleResolution": "node",
"rootDir": "src",
"noImplicitAny": true,
"typeRoots": ["./src/types", "./node_modules/@types"]
}
}
答案 0 :(得分:1)
像其他TS文件一样,在files / include下添加types目录。假设所有源文件都在src
中,那么这应该可以工作:
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"module": "esnext",
"target": "es5",
"lib": ["es2015", "es2017", "dom"],
"moduleResolution": "node",
"rootDir": "src",
"noImplicitAny": true
// This is automatically done by "moduleResolution": "node"
// "typeRoots": ["./node_modules/@types"]
},
// Also make sure to add any other directories as needed
"include": ["src/**/*"]
}