Repository navigation
disable certain global types for specific files, or specify type roots for specific files. #37053
Description
Activity
- addedAwaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScriptAn idea for TypeScript
on Feb 26, 2020 The main concept is that we often need to install
@typespackages as devDependencies to use global types in things like tool configurations, scripts, tests, etc, and then those global types leak into source files (although they actually aren't available at runtime in those files).If someone tries use a
describe()test function (for example) in a source file instead of a test file, then at runtime this will be an error.The idea here is that some option would allow us to specify which files certain
typesortypeRootsapply to, and our configuration would allow intellisense in editors like VS Code to show autocomplete options for APIs likedescribe()(for example) only in test files.Reacted by Yaroslav, Sam Wight, Dave, Alexey Ryabov, Mark Penner, Kesupile, Ibrahim ben Salah, ryan-0324, Malte Jürgens and Richard HermanThe the new
compositefeature (described in the Project References doc) solve this request? Does it allow globals to be scoped per project?The doc says
Previously, this structure (f.e. having both test/ and src/ folders that can import from each other) was rather awkward to work with if you used a single tsconfig file:
- It was possible for the implementation files to import the test files
This seems to imply that isolation of globals may be possible (f.e. so that things like
describe()andit()in test files don't leak into source files) .EDIT: Yes,
composite(Project References) does allow segregating global types per each reference. However, migrating from regular projects to project references can be cumbersome and lead to issues requiring refactoring, which is not ideal. Having an option that works with or without (tangential to, agnostic of) project references would be great.This issue keeps popping up the more TS projects I work on.
What we need is a more robust way of managing which global types are included or excluded. A couple cases are illustrated next.
Case 1: ergonomics:
Setting
typesto an empty array and manually listing all global types only to exclude, for example, a single global lib, is not ideal.For this use case, we simply need a way to exclude certain global types.
Case 2: libraries with global builds and modules:
The
threepackage on NPM can be imported as ES Modules, and the type defs work that way. However, that package also includes global types for people that may be using a<script>tag to load the lib as a global variable. When this package is added to a project, then even if we wish to use ES Modules for all types, the global types are still available (although the global variable itself is not), so this error can happen:import {Camera} from 'three' // all good, no type or runtime error const camera = new Camera // no type error, but runtime error "can't read property Scene of undefined" const scene = new THREE.Scene
For this use case, we simply need a way to exclude certain global types.
Case 3: multiple libs in a project depend on the same global namespace, but expect different types
Sometimes a project needs to use both React (for old parts of the code base) and some new library that also relies on JSX (for new parts of the code base). What ends up happening is that both React and the new lib (f.e. Solid.js, Preact, and a bunch of others) need to define
JSXtypes. Libs that depend on JSX types don't all define the JSX types in a way that plays nicely with each other (React doesn't because it assumes to be the king, but Preact does) so what can happen is conflicts in JSX type declarations.For this case, it would be great to be able to control which global types are available for which sets of files (I imagine it similar to a paths mapping, but mapping sets of files to type roots or similar). Then the project author can put React files in one place, and other-library files (f.e. Preact files or Solid.js files) in another place, and simply configure which files particular global types are available to.
An alternate existing solution for this case is to split the project into multiple TypeScript Project References, but this can be cumbersome and lead to other issues.
Having an option to control which globals are available to which files (which is a more fine-grained control than just "which globals to exclude" with the set of files to which we control global visibility being the whole project, as shown in the previous cases) would be useful here, without needing to restructure a project and introducing new issues. Furthermore, this option could still be helpful in Project References (it is tangential, and can be an option that works in any tsconfig.json, regardless if that tsconfig.json is for a project reference).
Case 4: source files vs test code
Projects often include both
.tsand.test.tsfiles co-located with each other (f.e.src/foo.tsis next tosrc/foo.test.ts). We may want certain global types available only in the test code (f.e.describe,it,expect, etc) but not in the source code.For this case the solution is the same one suggested for Case 3, for example exposing or excluding some globals to or from one set of files.
Here's a set of issues with people effectively asking for more control over global types:
- Can't disable type definitions for one special library #17042
- Suggestion: add excludeTypeRoots to tsconfig #18588
- TypeScript "exclude" conflicts with types resolution vscode#10285
- Impossible to exclude original declaration file from module #21189
- Don't include all @types/ automatically, only dependencies from package.json #11917
- typeRoots does not exсlude typings in node_modules #15933
- https://stackoverflow.com/questions/48704043/exclude-types-typings-in-installed-dependencies
- https://stackoverflow.com/questions/52621222/how-do-you-exclude-global-types-declared-in-typescript-definitions
- https://stackoverflow.com/questions/48427807/tsconfig-how-to-ignore-types-whatever-node-modules-for-a-specific-directory
- https://stackoverflow.com/questions/56188867/conflicts-with-global-types-in-typescript
- https://stackoverflow.com/questions/58507122/how-to-exclude-types-from-typescript-global-cache-users-user-library-caches
- https://stackoverflow.com/questions/41558661/ignore-bundled-d-ts-and-use-external-declarations
Ryan Cavanaugh (@RyanCavanaugh) Hoping this comment can satisfy the
Awaiting More Feedbacktag. (I'll move this comment to the OP)Reacted by Ben Wittenberg, Stefan Dirix, Kesupile, Ibrahim ben Salah, dominictobias-bullish, Pavel Horal, ryan-0324, Malte Jürgens, Ítalo Masserano, repulsio and 3 more- Reacted by Alexandre Galays, James Newell, Matthew Brown, Hunter Kohler, Laura, electrovir, Sam Wight, Hitko Development, Kevin Fleischman, Yudai Nakata and 22 more
This seems to be the current proposal:
https://gist.github.com/RyanCavanaugh/702ebd1ca2fc060e58e634b4e30c1c1cEach file's global scope is determined individually
Really not a fan of that idea. Excluding type packages with file globbing sounds much nicer.
Fallenstedt commented
on Nov 19, 2020 More actionsI experienced a global clash issue today, and reproduced it here
https://github.com/Fallenstedt/ts-globals-clashSay you had a monorepo with two packages
aandb.auses the jasmine test runnerbuses the jest test runner
The problem is
b's test files are only reading jasmine types...when they should have jest types. Having the ability to exclude types for specific directories would be amazing. We are at the mercy of teams using the global feature of typescript well. Having a way to correct their mistakes would be great!Reacted by Dave, Evan Jacobs, Brian Cooper, dominictobias-bullish, Amanda McGivern and Hal CarletonRyanCavanaugh commented
on Nov 20, 2020 MemberMore actionsExcluding type packages with file globbing sounds much nicer.
This is just going to create compile errors in lib files that need them (and they surely must need them, otherwise they wouldn't reference them in the first place). The problem here isn't that random definition files end up in your program, the problem is that transitive dependencies end up in your program even though they're immaterial to your particular use case.
Reacted by Jesse Jackson, Robin Curbelo and GabenGarHello everyone and Ryan Cavanaugh (@RyanCavanaugh) (and Alec Larson (@aleclarson) because you pointed out Ryan's proposal).
I've come up with a new compiler option idea that may solve some of the problems above (unless I missed that such a solution already exists):
The hypothetical new
declareOnImportOnly, when set totrue, would prevent global and module augmentations from running unless you explicitlyimportthe file that the augmentation code is inside of.Rather than all
declare globalanddeclare moduledefinitions eagerly making their way into your scope from any file in your project (including node_modules), they will all stay out, unlessimported.This seems like a very practical and standard role for
importsyntax to have (because you get what you import).To make this work well, you'd want to import particular files into your project, rather than simply importing package index files that import everything you may not use (this good practice also helps reduce bundle size without any tooling).
Reacted by Max Nanasy and Ricardo Valero de la RosaThe reason for my previous comment is, apparently, global types are picked up even when
tsconfig.jsoncontains"types": [], "typeRoots": []
and you've imported anything from a package that has global types (even if you never import the files that
declare global). It completely ignoretypesandtypeRootsin this case.The problem here isn't that random definition files end up in your program, the problem is that transitive dependencies end up in your program even though they're immaterial to your particular use case.
Ryan Cavanaugh (@RyanCavanaugh) Another problem is that some parts of one project need certain globals, while other parts of a project need other globals.
For example, having two forms of JSX in a project where some files need to pick up React's global JSX, and in the other files we want some other JSX types without React's JSX types polluting global.
Reacted by Max Nanasy, dominictobias-bullish, ryan-0324 and codethiefEveryone has the same issues, which indicate something must be done.
A purely browser project shouldn't be forced with ambient node types which almost always end up being loaded (I don't think we can fix it at this level as it would require every single lib and their dependencies to be a good actor) and pollute the global namespace.
Reacted by Alec Larson, signed, Gustavo, Matthew Brown, Laura, Leandro Aguiar, Corbin Crutchley, Dave, pragmat1c, John and 6 moreRyan Cavanaugh (@RyanCavanaugh) I have a suggestion for your proposal.
In addition to setting
strictEnvironment: true, projects should have the option to include a specific@typespackage in any file matching a defined glob. My suggestion is to let thetypesoption be a "glob map" like below:// tsconfig.json { "compilerOptions": { "strictEnvironment": true, "types": { "**/__tests__/**": ["jest"], "src/node/**": ["node"], "src/client/**": ["lib:dom"], // Maybe allow lib definitions too? } } }
edit: On second thought, once
strictEnvironmentlands, this will be achievable by creating onetsconfig.jsonper glob.// tsconfig.test.json { "include": ["**/__tests__/**"], "compilerOptions": { "strictEnvironment": true, "types": ["jest"] } } // src/node/tsconfig.json { "compilerOptions": { "strictEnvironment": true, "types": ["node"] } } // src/client/tsconfig.json { "compilerOptions": { "strictEnvironment": true, "lib": ["dom"] } }
But would I need two
tsconfig.jsonfor tests (one with[ jest, node ]and the other with[ jest, dom ]), or wouldtsconfig.test.jsonmerge with the other two when they match the same file?Reacted by Henrik Friberg, rhzone, Max Kayander, Kesupile, Lucas Garron, Seyyed Mahdi Hassanpour and dominictobias-bullishOne other use case for this would be when a misbehaving package adds a global type that it shouldn't.
For example,
@apollo/clientadds the following:declare global { interface Observable<T> { ['@@observable'](): Observable<T>; } }
(https://cdn.jsdelivr.net/npm/@apollo/client@3.3.12/utilities/observables/Observable.d.ts)
This conflicts with
rxjs's ownObservablewhich creates editor issues in VSCode. A way to override this at the project level would be great.See:
apollographql/apollo-client#7839While this can be resolved by manually adding the import. It breaks editor auto import functionality as the editor thinks Observable is already a known type. This is a major pain as rxjs/Observable is used in nearly everywhere (angular app).
yeah....I really need this. I try to develop a plugin under typescript for Blockbench, which is a combined environment under electron. .Its need lib.dom.d.ts type but its override some lib.dom.d.ts global type in plugin context. And its drive me crazy, since it just simple won't work caus of duplicated declared problem and seems not possible to override the global object under typescript d.ts which can be done under javascript. I guess I have to made a custom lib.dom.d.ts type as workaround :/
17 remaining items
Can somebody please summarize in short what the problem is in regards to why there's not much progress and this issue is still not solved after three years, given how serious it is? It's obvious that a glob pattern is needed (as OP already mentioned), because the problem is on a file basis.
Reacted by Adam Spiers and Devin RiegleCan somebody please summarize in short what the problem is in regards to why there's not much progress and this issue is still not solved after three years, given how serious it is? It's obvious that a glob pattern is needed (as OP already mentioned), because the problem is on a file basis.
@gernotpokorny Other tasks have been identified to be more important.
TypeScript is Free Open Source Software, so anyone (including you and me) can fix the issues — and even contribute our fixes upstream (using the Pull Request feature), so that everyone can benefit.
Reacted by Adam Spiers, Matthew Dean, Richard Simko and Sam WightJesse Jackson (@jsejcksn) What is more important then having clean types in TypeScript? ^^
Shouldn't this be at the top of the list after critical bugs?
Reacted by Adam Spiers, dominictobias-bullish and Sam WightIf you use eslint, you can use this rule https://eslint.org/docs/latest/rules/no-restricted-globals to disable some globals
If you want to enable/disable on certain file, you can use either
/* eslint-disable no-restricted-globals */at the beggining of the file or use overrides proprerty ineslintignoreto match a given list of patternReacted by Marvin HeilemannThis may now be solved with
extendsin v5.0.0 though I haven't confirmed this personally yet:TypeScript is Free Open Source Software, so anyone (including you and me) can fix the issues — and even contribute our fixes upstream (using the Pull Request feature), so that everyone can benefit.
Nice copout. What do you gain from it?
Consider the differential between the complexity of the TypeScript codebase vs. the resources of any individual developer blocked by any particular issue.
Consider that there is no guarantee that the proposals of contributors outside Microsoft will be included: in my experience, maintainers react with "idk what this guy is talking about" to issues that do not further the product agenda - regardless of years upon years of valid arguments provided by the community.
Do you honestly expect all PRs to be reviewed in good faith?
Of course, TS devs are a competent bunch, so they excel at making excuses for TS being ridden with antifeatures that disallow people from just solving their own problem. See #18588 - or this absolutely brilliant and totally fair rationale for closing #14979:
typeRoots is rather an advanced feature. that and the limited number of these folder, suggest that this can be left to humans to figure out, and does not need to be done by the compiler.
I'd rather humans be left to figure out the correctness of types for themselves, too: by writing tests to verify their code actually works - rather than delegating about half of that task to a static analysis tool that also, by necessity, is a compiler, then disregarding the other half. However, my coworkers only know TypeScript. They do not seem to know JavaScript. Or testing. I like them, and I like where I work. So I'm stuck wrangling TS, too - for mine and their sake.
For example, let's say I want to include
.and exclude./distintypeRoots. Am I dumb or is there no way to specify that? Glob is not supported, exclude is not supported... what then? Move all my code under./src? Sure, "everybody does that", and I could totally do that, too - except what if I have a valid reason not to? If TS was committed to doing things compatibly and correctly, one wouldn't need to adapt their workflow to accommodate the blind spots of a bunch of Microsoft people that act deaf to the frustration of their fellow programmers.The FOSS solution would be to fork TypeScript - and then the community would be forced to forever maintain an "alternative TS", that would slowly grow incompatible with upstream (just like TypeScript is now practically incompatible with JavaScript, talk of "supersets" notwithstanding). Good luck getting people to know about it and switch over!
Boo, Microsofties. Shame on you. Instead of accommodating developers' needs, you keep gaslighting them into exhausted compliance. I hope one day every TS dev and TS apologist learns the error of their ways. Right now, I'd say TS5 sucks about 10% less than TS4, so maybe in TS6 another batch of papercuts that wasted innumerable dev hours will be resolved 🤞
Sorry, your comment struck a nerve there. I stand by my words, though: TypeScript is fake "Open Source Software".
P.S. I've got half a mind to email the downvoters and ask them when was the last time they got a PR merged into TypeScript. But instead, I'll just leave this here https://graydon2.dreamwidth.org/306832.html and leave you to experience your knee-jerk reactions - I've got some AST rewriters to implement...
Reacted by Yue JIN, Patrick Roza, dominictobias-bullish and GabenGarReacted by Philip Cox, Dave, iwatachan, AⱯ, Yuki Minoh, Luna, Daniel Leavitt, Randall Leeds, James Mulholland, Malte Hallström and 1 moreReacted by Simon LagosCan somebody please summarize in short what the problem is in regards to why there's not much progress and this issue is still not solved after three years, given how serious it is? It's obvious that a glob pattern is needed (as OP already mentioned), because the problem is on a file basis.
@gernotpokorny Other tasks have been identified to be more important.
TypeScript is Free Open Source Software, so anyone (including you and me) can fix the issues — and even contribute our fixes upstream (using the Pull Request feature), so that everyone can benefit.
Jesse Jackson (@jsejcksn) is there a solution to this problem that core typescript maintainers have indicated support for that someone from outside that core group could implement and PR upstream? the only comments in this thread from a core member are #37053 (comment) (in which Ryan Cavanaugh (@RyanCavanaugh) indicates that a file glob pattern solution is inviable) and #37053 (comment) (in which Ryan Cavanaugh (@RyanCavanaugh) reiterates that the “linked suggestion doesn't really solve anything IMO”).
over in #52433, which requests support for treating libs as a union (not an intersection, as they are right now) in order to support type checking code that runs in multiple environments, there’s #52433 (comment), which again indicates a posture that is generally closed towards any of the proposed solutions (“The problem we've had here in the past is that a huge amount of code can be seen to be running in one environment by inspection, but not in a way that's susceptible to static analysis.”), but it does end with this:
There's nothing today stopping someone from auto-genning variant DOM/webworker/etc libraries with every top-level declaration marked possibly-
undefined. Real-world usage of such output would be good evidence that this kind of feature would be usable in practice.that’s a suggestion for a user-land-based solution that would help with the isomorphic problem-space described in #52433, but would do nothing to help with the issue here as described by Ryan Cavanaugh as:
transitive dependencies end up in your program even though they're immaterial to your particular use case
all of this leaves me with two questions:
- what is the solution for this problem that someone could work on that has any indication of support from any core typescript team members?
- has anyone tried to auto-gen variant DOM/webworker/etc libraries with every top-level declaration marked possibly-
undefined? if no one has, i’d be happy to give it a go and try to see if it solves any problems, though as a library consumer, not a library author, i’m not sure if there’s an existing auto-gen tool i can use to do that or if the assumption is that whoever creates those libs would need to also create the tools needed to parse and transform the existing libs in the way suggested. what i really want is to do something likeimport type * as DOMTypes from 'dom'; export type OptionalDOM = Partial<DOMTypes>;, so that i could continue to rely on the libs and not have to maintain a fork, but 🤷.
Reacted by AⱯ, Alexander Pepper, Luna, Yuki Minoh, Lucas Garron, Damien Lajarretie, Ze-Zheng Wu, codethief and Sam WightDriving me nuts. JSX is becoming a more and more popular choice on the server, but as soon as a React project imports anything from the server, like a strong typing contract for the API, all types in React break because the non-React JSX redefines JSX globally
Reacted by Luna, Yacine Hmito, Sam Wight, GabenGar and repulsioAndrew Patton (@acusti) What I got from this whole debate is that the right way of dealing with this issue would be for libraries to provide a separate
globals.d.tsfile, and for the developers to include it as{ "types": ["library/globals"] }only where they actually rely on particular global values.However, doing it that way is discouraged by the fact that most users would view it as an inconvenience rather than a feature, as well as being a major change for existing libraries, many of which are no longer actively maintained in the first place. So other than doing it the wrong way, I don't think there's another practical solution to this issue.
Reacted by AⱯ, Andrew Patton, Yuki Minoh and repulsioIt's absolutely wild that importing any library that happens to have
/// <reference types="node" />as a part of their type defs will leak the Node types to the current project's global scope and there is no setting to avoid this behavior. IMO this is a huge foot gun and a massive bug in TypeScript and goes against the very purpose of having a type check.For example importing a type from a library to use in a shared API interface (Which then gets imported in the client side code) will leak NodeJS types to the client.
Reacted by Dave, Lucas Garron, Andrew Patton, GabenGar, Sam Wight, AⱯ, Marcus Blättermann, Simon Lagos, Florian Mt, Hal Carleton and 17 more- added a commit that references this issue
on Jun 19, 2025 Is it possible to get more clarity on what kind of information is still missing to make this issue to still have the "Awaiting more feedback" tag?
Reacted by repulsio, Lucas Garron and Max Waibel@types/nodeleaking into my browser projects out of my control is killing my dev experience...Reacted by AⱯ, Corentin and Kirk Holloway@types/nodeleaking into my browser projects out of my control is killing my dev experience...You can workaround the issue with something like this. You will have to explicitly list any
@typespackages you add, and remove them if you remove a project, but it can at least protect you from Node types leaking into browser project."typeRoots": [ "./node_modules/@types" ], // add any @types here, empty array instead of default to prevent @types/node from being picked up "types": [],
Reacted by repulsio- added a commit that references this issue
on Feb 3, 2026
This continues some ideas from #17042, which was closed by Microsoft (@microsoft) (for inactivity, I think?).
Search Terms
disable certain global types for specific files, specific type roots for certain files
Suggestion
Ability to specify which
@types(or in general, which specifiedtypeRoots) apply to which files in a project.Use Cases
My project's
srcfolder contains both.tsand.test.tsfiles, and I'd like an easy way for globals likedescribeto be defined only for the.test.tsfiles.Examples
Not sure, but maybe some sort of new options in
tsconfig.jsonfor specifying whichtypesitems,libitems, ortypeRootsitems apply to which files.This would be a beneficial feature because various editors (VS Code aside) look for a
tsconfig.jsonfile at the root of a project, and at the moment the only way to make types work in all files is to just provides all types for all files, which is undesirable becausedescribeis not a function that is available in source files (as an example).Example configuration: maybe instead of a
typeRootsarray, it can be an object like:Or something. That's just an example to get the idea rolling.
Checklist
My suggestion meets these guidelines: