Import/Require nodejs modules without @types in Typescript in 2018

I have a typescript nodejs project for a website. I need to use functionality that is available in this specific nodejs module: https://www.npmjs.com/package/weather-js

This module does not have a .d.ts file available in its repository, nor is there one available in the ‘@types’ typescript repository. I do not require type definitions for this module, but typescript does not include it and produces errors.

No matter which way I try to import, I either get

TS2304: Cannot find name 'require'.

in the build console, or

TypeError: qs.escape is not a function

in the browser dev console.

Many responses here on StackOverflow suggest solutions that require repositories that are no longer available in 2018, or that might work but for me still produce the error

TypeError: qs.escape is not a function

What is the correct way to use/import/require/consume nodejs module functionality (without .d.ts definitions available) in typescript in 2018?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You can add a dummy definition to allow it to import but without actually typing the module contents (although maybe if you should type them fully and submit to DefinitlyTyped so the everyone can benefit from type safety too!)

weather-js.d.ts

// declaring module will allow typescript to import the module
declare module 'weather-js' {
  // typing module default export as `any` will allow you to access its members without compiler warning
  var weatherJs: any; 
  export default weatherJs;
}

yourCode.ts

import weather from 'weather-js'

weather.find({search: 'San Francisco, CA', degreeType: 'F'}, () => {})

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply