简体   繁体   English

TypeScript 不会推断 CommonJS 导入的类型(通过 require())

[英]TypeScript does not infer the type of CommonJS import (through require())

  • My code runs in Node.js environment.我的代码在 Node.js 环境中运行。 I have installed @types/node .我已经安装了@types/node When I write import http = require('http') or import * as http from 'http' , the type of the object I'm importing is inferred:当我写import http = require('http')import * as http from 'http'时,推断出我正在导入的对象的类型: 在此处输入图像描述
  • However, when I write const fs = require('fs');但是,当我写const fs = require('fs'); , the type is any . , 类型是any Why is that?这是为什么? Can I do anything about it?我能做些什么吗?

在此处输入图像描述

TL;DR TL;博士

A possible fix for this is to import the types for Node.js.一个可能的解决方法是导入 Node.js 的类型。


Full Solution完整的解决方案

The solution for this issue is to import the types for Node.js.此问题的解决方案是导入 Node.js 的类型。

This is available as an npm package .这是一个npm It contains all of the types for Node.js.它包含 Node.js 的所有类型。

To install it, you need to run the following command.要安装它,您需要运行以下命令。

$ npm install --save-dev @types/node

The reason the --save-dev flag is on the install command is because it isn't supposed to be a dependency, but instead a dev (development) dependency. --save-dev标志出现在 install 命令上的原因是它不应该是依赖项,而是一个开发(开发)依赖项。 This will not install this package if, for example, your project is installed as an npm module.例如,如果您的项目安装为npm模块,则不会安装此包。

After this, IntelliSense will automatically pick up the type definitions, and will add auto-correct your Node.js code, including doing some other handy things.此后, IntelliSense将自动获取类型定义,并添加自动更正您的 Node.js 代码,包括做一些其他方便的事情。


If the type definitions don't get picked up, then the best solution is to restart Visual Studio Code.如果没有选择类型定义,那么最好的解决方案是重新启动 Visual Studio Code。 If that doesn't work, make sure that this is in your package.json file.如果这不起作用,请确保它在您的package.json文件中。

{
  "devDependencies": {
    "@types/node": "^17.0.31"
  }
}

Note: The version was correct at the time of post.注意:发布时版本是正确的。

If it isn't, then add that code in your package.json file, save it, and run the following command.如果不是,则将该代码添加到您的package.json文件中,保存并运行以下命令。

$ npm install

This should install it successfully.这应该成功安装它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM