How to use Typescript DOM lib on the server?

1.3k views Asked by At

I am writing code for a Google cloud function. Here I want to use the URL standard including URLSearchParams. I found out that they are part of the TypeScript DOM lib, so I've added that to my tsconfig lib setting.

However, when I compile and deploy the cloud function I get a runtime error saying URLSearchParams is not defined.

What am I missing? I'm using TS 2.6


Here is my config:

{
  "compilerOptions": {
    /* Basic Options */
    "target": "es6",
    "module": "commonjs",
    "lib": ["es6", "es7", "esnext", "dom"],

    "sourceMap": true /* Generates corresponding '.map' file. */,
    "outDir": "build" /* Redirect output structure to the directory. */,
    "removeComments": true /* Do not emit comments to output. */,

    /* Strict Type-Checking Options */
    "strict": true /* Enable all strict type-checking options. */,

    /* Additional Checks */
    "noUnusedLocals": true /* Report errors on unused locals. */,
    "noUnusedParameters": true /* Report errors on unused parameters. */,
    "noImplicitReturns": true /* Report error when not all code paths in function return a value. */,
    "noFallthroughCasesInSwitch": true /* Report errors for fallthrough cases in switch statement. */,

    "plugins": [{ "name": "tslint-language-service" }],
    "skipLibCheck": false
  },
  "include": ["src/**/*"],
  "exclude": ["build"]
}

And package.json dependencies:

  "dependencies": {
    "circular-json": "^0.4.0",
    "es6-promisify": "^5.0.0",
    "firebase-admin": "^5.5.0",
    "firebase-functions": "^0.7.3",
    "invariant": "^2.2.2",
    "joi": "12",
    "lodash": "^4.17.4",
    "node-fetch": "^2.0.0-alpha.9"
  },
  "devDependencies": {
    "@types/circular-json": "^0.4.0",
    "@types/invariant": "^2.2.29",
    "@types/joi": "^13.0.0",
    "@types/lodash": "^4.14.85",
    "@types/node": "^8.0.52",
    "@types/node-fetch": "^1.6.7",
    "cpy-cli": "^1.0.1",
    "del-cli": "^1.1.0",
    "firebase-tools": "^3.15.1",
    "tslint": "^5.8.0",
    "tslint-config-prettier": "^1.6.0",
    "tslint-language-service": "^0.9.6",
    "typescript": "2.6"
  }
1

There are 1 answers

2
Fenton On

You just need to update your compiler options to include dom:

Before:

"lib": ["es6", "es7", "esnext"],

After:

"lib": ["es6", "es7", "esnext", "dom"],

This is the library with the URLSearchParams interface.

With just the above change, I can place the following in src/sub/temp.ts:

let x: URLSearchParams;

And I get the following type information on hover, plus autocompletion.

interface URLSearchParams
var URLSearchParams: {
    new (init?: string | URLSearchParams | undefined): URLSearchParams;
    prototype: URLSearchParams;
}

There are zero compiler warnings.

This is all based on TypeScript v2.6.1... you aren't using an older version are you (pre v2.2?).