14

I have a Node.js project that is built with TypeScript I'm trying to use URLSearchParams, however I can see the following error:

Cannot find name 'URLSearchParams'.ts(2304)
const params = new URLSearchParams();
params.append("foo", 5);

typescript: ^3.9.7
node.js: v12.16.3
Audwin Oyong
  • 2,247
  • 3
  • 15
  • 32
Kay
  • 17,906
  • 63
  • 162
  • 270
  • @jenson-button-event really i jsut found this works ```import {URLSearchParams} from "url";``` – Kay Aug 04 '20 at 12:58
  • https://nodejs.org/api/url.html#url_class_urlsearchparams – Kay Aug 04 '20 at 12:58
  • 1
    Im confused why i need to import it from "url" when it says "The class is now available on the global object." – Kay Aug 04 '20 at 12:59
  • Where do you see this message 'The class is now available on the global object'? Perhaps it only applies to the dom environment, and not node? – g2jose Aug 04 '20 at 13:17
  • **See Also**: [How to use global URLSearchParams in node](https://stackoverflow.com/q/47266550/1366033) – KyleMit Sep 27 '20 at 13:04

1 Answers1

33

While URLSearchParams has lived on the global object in node since v10.0.0, it can be hard to pull ambient type information from there.

The URLSearchParams class lives in the url module, so you can also import it directly from there:

import { URLSearchParams } from "url"

then use it like this:

let queryString = new URLSearchParams({page: "1", pagesize: "100"}).toString();

Also, make sure you install types for node

npm install @types/node --save-dev

Further Reading

KyleMit
  • 30,350
  • 66
  • 462
  • 664