-
Notifications
You must be signed in to change notification settings - Fork 13.3k
Description
Bug Report
🔎 Search Terms
avoid dom lib, compile without dom, exclude lib.dom.d.ts
Related to:
- Duplicate identifier error caused by lib.dom.d.ts #35578
- DOM library in not excluded even when lib does not have dom #43929
- Lib dependencies are transitive #37775
- Node module dependencies that use a triple-slash directive to reference libs poison the global scope #33111
- StackOverflow: Using TypeScript without DOM types (for node)
🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about 4.2.3
⏯ Playground Link
Reproducing the problem requires to have dependencies installed, which makes it impossible to reproduce on Playground as far as I can see.
Instead I can offer a self-contained minimal reproduction example here.
💻 Code
In a nodejs backend application, the following code is supposed not to compile:
const time = performance.now();because in nodejs it requires an explicit import { performance } from "perf_hooks" in contrast to browser code.
The tsconfig.json specifies lib: ["es6"], which according to the docs (and various SO questions) should result in not adding dom types to the compilation.
In addition the project also has npm-installed third party dependencies, in particular @types/superagent.
🙁 Actual behavior
The code compiles successfully.
In fact, we just had our first production backend crash, because one performance.now() slipped through without an explicit import, which clearly should have been caught by the compiler.
🙂 Expected behavior
The code should not compile, as it does before having installed @types/superagent.
Thoughts
The reason why this happens is that the @types/superagent contains a triple slash directive in their type definitions:
/// <reference lib="dom" />Note: Such problems can also be caused transitively. In our case, the culprit was actually hidden behind npm install --save-dev @types/supertest which transitively brought in the problematic dependency.
Can we simply blame these type definitions and convince the maintainers to "fix" that? Probably not. Having a look at the type definitions, what they do makes sense. The library supports both node and browser contexts, and in a browser context certain types (mainly appearing in union types anyway) are e.g. valid input types. Also, the problem could possibly come up in many more dependencies, i.e., another (future) dependency could break the "strict nodejs types" at any time.
Clearly, third party dependencies should not cause false positive compilations in a non-browser context. Perhaps the most sensible solution would be to consider the /// <reference lib="dom" /> only for the compilation of that particular type definition file, but not to "hoist" it into the compilation of the user code. I.e., if the user omits "DOM" from the lib setting it should be respected for all user code.