gpt4 book ai didi

javascript - CommonJS + node-fetch 不可用的 Intellisense 类型

转载 作者:行者123 更新时间:2023-12-05 06:04:01 28 4
gpt4 key购买 nike

问题

使用流行的 node-fetch库,Intellisense 不理解 fetch() 的返回值。

带有 coc 的 Vim:

inspecting the return type of fetch, I see const result: any

VSCode 中的相同内容:

same thing in VSCode

对于大多数其他库,我有类型完成功能,但这个不起作用。

我尝试过的事情

  1. 添加了 jsconfig.jsontsconfig.json 文件
  2. 调查了导出 @types/index.d.ts
  3. 的包
  4. 尝试安装 @types/node-fetch,它也经常过时
  5. 转换为import语法,有效

预期结果

正如我提到的,更改为 import 语法可以解决问题,但我希望它也能与 require 一起使用。

enter image description here

我如何使用 CommonJS 在这个库上进行类型补全?

最佳答案

解决方案

const fetch = require('node-fetch').default

解释

为了弥合 CommonJS 和 ES 模块语法之间的根本差异,require('node-fetch') 返回具有以下形状的对象:

node REPL showing the result of node-fetch as an object with a property called default

注意 node-fetch type definition 确实fetch() 函数导出为顶层,但也导出了一个 default 属性以与 ES 模块语法兼容。使用此属性可修复自动完成问题。

enter image description here

这对我来说仍然像是一个错误,但这个解决方法确实解决了这个问题。

关于javascript - CommonJS + node-fetch 不可用的 Intellisense 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66484663/

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