Intellisense types unavailable with CommonJS + node-fetch

Issue

Using the popular node-fetch library, Intellisense doesn’t understand the return value of fetch().

Vim with coc:

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

Same thing in VSCode:

same thing in VSCode

For most other libraries I have type completion, but this one does not work.

Things I tried

  1. Added jsconfig.json and tsconfig.json files
  2. Investigated the package, which exports a @types/index.d.ts
  3. Tried installing @types/node-fetch, which also falls out-of-date often
  4. Converted to import syntax, which works

Expected result

As I mentioned, changing to import syntax fixes the issue, but I want it to work with require too.

enter image description here

How can I have type completion on this library with CommonJS?

Answer

Solution

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

Explanation

To bridge fundamental differences between CommonJS and ES module syntax, require('node-fetch') returns an object with this shape:

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

Notice the node-fetch type definition does export the fetch() function as the top level, but also exports a default property for compatibility with ES module syntax. Using this property fixes autocomplete issues.

enter image description here

This still seems like a bug to me, but this workaround does resolve the issue.

Leave a Reply

Your email address will not be published. Required fields are marked *