commscheck
commscheck

Reputation: 453

How do I use URLSearchParams and similar APIs when writing an isomorphic Typescript package?

I'm trying to write a package in Typescript that is usable in both the browser and Node ("isomorphic"). The purpose of the package is to provide typed endpoints of a website's REST API.

I've only specified "lib": ["ESNext"] in my tsconfig.json file, since DOM APIs aren't available in Node, and vice-versa.

I want to provide a URLSearchParams object to an Axios request. My understanding is that URLSearchParams isn't a built-in Javascript type, but exists globally in both browser and Node v10+. But since I haven't specified "lib": ["DOM"] in my tsconfig file, and haven't added @types/node to the project, the class isn't available.

How do I use APIs like URLSearchParams and still support both browser and Node?

My full tsconfig.json file:

{
  "include": ["src"],
  "exclude": ["node_modules", "dist"],
  "compilerOptions": {
    // Type Checking
    "noFallthroughCasesInSwitch": true,
    "noImplicitOverride": true,
    "noImplicitReturns": true,
    "noPropertyAccessFromIndexSignature": true,
    "noUncheckedIndexedAccess": true,
    "strict": true,
    "strictBuiltinIteratorReturn": true,

    // Modules
    "module": "NodeNext",
    "moduleResolution": "nodenext",
    "noUncheckedSideEffectImports": true,

    // Emit
    "declaration": true,
    "declarationMap": true,
    "downlevelIteration": true,
    "outDir": "dist",
    "sourceMap": true,

    // Interop Constraints
    "isolatedModules": true,

    // Language and Environments
    "lib": ["ESNext"],
    "target": "ES2015",

    // Projects
    "composite": true,
    "incremental": true
  }
}

Upvotes: 1

Views: 28

Answers (0)

Related Questions