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

标签 javascript node.js intellisense

问题

使用流行的 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/

相关文章:

javascript - 按钮在表格行内不起作用

javascript - 检查一个单词是否有多个字母

javascript - Twilio 可编程视频聊天室

javascript - Moment.js 返回 "December 31, 1969"

javascript - 用于传递参数的 jQuery-Intellisense

javascript - 如何将从谷歌应用程序脚本 HTMLService 类获取的模板插入到 .html 文件中?

javascript - 如何检测Web App是否被CocoonJS封装

javascript - 我的 $scope 变量中的元素不会显示

c# - 识别 Visual Studio 中的一次性对象?

javascript - 为 .NET 类生成 Javascript 智能感知文件