Cha*_*uys 5 typescript nock axios
我正在尝试模拟axios使用 using发出的请求nock。此集成历史上存在一些问题,但此问题中描述的解决方法有效。当我将 Typescript 引入混合中时,出现了我的问题。虽然axios附带了主库的类型定义文件,但nock集成axios需要从子目录导入,如下所示:
import HttpAdapter from 'axios/lib/adapters/http';
Run Code Online (Sandbox Code Playgroud)
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';`
Run Code Online (Sandbox Code Playgroud)
我该如何修复这个错误?我尝试过各种自定义类型定义的组合,类似于axios:
// <project>/src/types/axios.d.ts
declare module 'axios/lib/adapters/http` {
import { Adapter } from 'axios';
const HttpAdapter: Adapter;
export default HttpAdapter;
}
Run Code Online (Sandbox Code Playgroud)
我对 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"]
}
}
Run Code Online (Sandbox Code Playgroud)
像其他 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/**/*"]
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4231 次 |
| 最近记录: |