gpt4 book ai didi

typescript - 如何在子目录中为模块添加类型定义?

转载 作者:行者123 更新时间:2023-12-04 15:59:07 27 4
gpt4 key购买 nike

我试图模拟使用 axios 提出的请求使用 nock .这种集成在历史上存在一些问题,但描述的解决方法 in this issue作品。当我将 Typescript 引入混合时,就会出现我的问题。虽然 axios带有主库的类型定义文件,nockaxios集成需要从子目录导入,如下所示:

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 不是很有经验,所以我的理论是我的自定义定义文件在错误的地方,使用了错误的模块名称,或者没有导出正确的东西。任何帮助将不胜感激。

附加上下文

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"]
}
}

最佳答案

像其他 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/**/*"]
}

关于typescript - 如何在子目录中为模块添加类型定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50954167/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com