What is @types/node package in NodeJs?

Viewed 14612

I'm using Node v10 and I found that I have dependency issue when using a library.

In the ldapjs library, lib\url.js uses const url = require('url') and then parsedURL = new url.URL(urlStr) to parse the string to URL.

I get this error:

Unhandled Rejection (TypeError): url.URL is not a constructor

with this line of code: parsedURL = new url.URL(ldapurl) in my React project.

However, under my environment, 'url' actually refers to node_modules\@types\node\url.d.ts which doesn’t contain any .URL(str) method, thus the error.

What is @types/node? Is it related TypeScript? I don't use TypeScript in my project. Can I remove it?

If I run Node in the terminal, it works fine:

> const url = require('url')
undefined
> let purl = new url.URL("https://google.com")
undefined
> console.log(purl)
URL {
  href: 'https://google.com/',
  origin: 'https://google.com',
  protocol: 'https:',
  username: '',
  password: '',
  host: 'google.com',
  hostname: 'google.com',
  port: '',
  pathname: '/',
  search: '',
  searchParams: URLSearchParams {},
  hash: '' }

What is the problem?

1 Answers

As taken directly from the @types/node npm package:

This package contains type definitions for Node.js (http://nodejs.org/).

This package is used to load in all type definitions when using typescript in node. When you add other packages, you also have to add their typings if they do not include them by default.

As an example, imagine you want to use lodash in your typescript application, you will need to install the type definitions (@types/lodash) too.

You don't need to worry about all this when you are not using typescript.

Related