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

为君一笑 提交于 2020-05-12 14:48:31

问题


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?


回答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'}, () => {})


来源:https://stackoverflow.com/questions/48224858/import-require-nodejs-modules-without-types-in-typescript-in-2018

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!