Import/Require 2018 年 Typescript 中没有 @types 的 nodejs 模块

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

我有一个用于网站的 typescript nodejs 项目。我需要使用此特定 nodejs 模块中可用的功能:https://www.npmjs.com/package/weather-js

此模块在其存储库中没有可用的 .d.ts 文件,'@types' 打字稿存储库中也没有可用文件。我不需要此模块的类型定义,但打字稿不包含它并产生错误。

无论我尝试以哪种方式导入,我要么得到

TS2304: Cannot find name 'require'.

在构建控制台中,或

TypeError: qs.escape is not a function

在浏览器开发控制台中。

Whosebug 上的许多回复建议的解决方案需要的存储库在 2018 年不再可用,或者可能有效但对我来说仍然会产生错误

TypeError: qs.escape is not a function

2018 年在打字稿中 use/import/require/consume nodejs 模块功能(没有可用的 .d.ts 定义)的正确方法是什么?

您可以添加一个虚拟定义以允许它导入,但无需实际键入模块内容(尽管如果您应该完整键入它们并提交给 DefinitlyTyped,这样每个人都可以从类型安全中受益! )

天气-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'}, () => {})