You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Specifying lib: DOM and WebWorker should not be mutually exclusive #20595
My project is designed to work either in the "main thread", with access to DOM, or as a WebWorker, where a different behavior kicks in. This was done for compatibility reasons and to have only one distributable js file and it's been working fine for the last two years.
In all this time I never specified the lib compiler option, only target ES5.
Today, as I'm experimenting some ES2015 stuff, I see that if I specify targets DOM,ES5,WebWorker,ES2015.Promise all hell breaks loose with errors. - Duplicate identifier, Subsequent variable declarations must have the same type.
Shouldn't this kind of mix be allowed in a project?
Reacted by Jozef Pazin, Michal Wisniewski, Teppei Sato, Jacopo Lanzoni, SilentTiger, Toru Nagashima, Gianpiero Caretti, Mike P, Philip Walton, Jacob Bogers and 63 more
Reacted by Jozef Pazin, Jakub Koralewski, Sebastian Müller, Troy Alford, Norman Fomferra, Réda Housni Alaoui, Joe Previte, Antonio Gargaro, nivaldo, Sergei Slipchenko and 1 more
Unfortunately the base APIs for WebWorker and DOM are actually meaningfully different, and it's not clear at this point how to write a clean separation of global scopes between different parts of your project other than splitting your project into multiple parts.
Reacted by Jacob Bogers, Kaelan Cooter, Max Coplan, Jonathan Doster, Ian Bellomy, Zachary Norman, Perry Mitchell and Jarrod Davis
We have found that what is meaningful in the global scope of a web worker is significantly more narrow than we find out of the DOM. So we tend to author with "lib": [ "dom" ] and then just declare the handful of APIs we require to make a web worker work, or we obtain a reference to the global object, treat it as any, and pick off certain properties from the global scope and type them at the point where we pick them off.
While it isn't ideal, it saves us from the only other realistic option, splitting the code. If you have modular code, and pick off parts of a global scope and type them, and you are using modular code, you should be able to author isomorphic modules fairly easily. Here is an example of the most "bullet proof" way to get a reference to the global scope, which avoids any issues with CSP:
constglobalObject: any=(function(): any{if(typeofglobal!=='undefined'){// global spec defines a reference to the global object called 'global'// https://github.com/tc39/proposal-global// `global` is also defined in NodeJSreturnglobal;}elseif(typeofwindow!=='undefined'){// window is defined in browsersreturnwindow;}elseif(typeofself!=='undefined'){// self is defined in WebWorkersreturnself;}})();
Reacted by Armand, Evgeny Lukashevich, ChasLui, Zeus, Olena Svietlova and Tobias Goulden Schultz
Kitson Kelly (@kitsonk) But, do I need to write your above code in every file? and use globalObject for referring properties
How do I handle this scenario in here?
Charles Bodman (@charlesbodman) Yes it works now. In JS, we have SharedWorker object. Am trying to execute the same code using let worker: SharedWorker = new SharedWorker('worker.js'); but I see the error Cannot find name 'SharedWorker'
I suppose the "right" approach would be for IDE support to better approximate compilation support by supporting multiple tsconfigs on the same folder that affect different combination of files. But that sounds hard and needs to be supported by the IDE proper as well.
I'm not sure what the correct approach is right now.
To add to my previous comment above: For libraries, there actually is a work around: It's also an all-or-nothing flag, so really having more control over this would be appreciated: Use the skipLibCheck option to disable checking of the .d.ts files that only compile cleanly in the "other" lib context.
Though it is a little bit ugly, here is a method I've gotten to work:
(self as unknown as Worker).postMessage(/* message */)
This actually makes the intellisense work on the postMessage correctly as well in VSCode, by correctly forcing recognition of the type of self. I dislike the as unknown in the middle, but without that, I get a different TS error:
Conversion of type 'Window & typeof globalThis' to type 'Worker' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
If there's a cleaner syntax for this, I'd love a hint. :)
Reacted by Max Coplan, Jonathan Doster, Ashyam90, Réda Housni Alaoui, OGGY KIM, Sebastian Pardo, Emilio Barrientos and Rob Royce
Orta Therox (@orta) and I put our heads together on this to see if Ryan Cavanaugh (@RyanCavanaugh)'s proposed solution is workable. So far, we think Yes, with some caveats that we need to investigate. Here's are some notes; we'll work more on this soon.
The core problem is that people need to include webworker at the same time as DOM, but several of the declarations conflict. (16 of them, currently).
When you look at the difference between webworker and DOM, the differences fall into 3 buckets:
a. New types and values specific to webworker. We believe this is most of what people want from including webworker.
b. Missing values and types that don't make sense for webworker. eg webworker doesn't have the type HTMLOrSVGImageElement. This is nice to exclude but not the highest priority.
c. Types that conflict and values with conflicting types.
Ryan Cavanaugh (@RyanCavanaugh)'s proposal to create a new dependent, lib.browser.d.ts, would solve (a) and (b) -- just put the core things into browser and let webworker or dom respectively extend the core.
The conflicts in webworker could be fixed in the following ways
A few are just out of date, like DOMMatrixReadOnly, CrytoKeyPairs
A few, like FormData's constructor or ImageBitmapRenderingContext.canvas, could extend a base in browser in an unsound way.
Callbacks like onlanguagechange, onoffline, ononline, onrejectionhandled, onunhandledrejection, could be made compatible with the DOM by removing the this parameter.
This leaves onerror and self.
self is defined in the same way for both files, but webworker uses the much smaller type WorkerGlobalScope instead of Window. If it used the name Window instead it would probably merge cleanly with the DOM's self, although I haven't tested this yet.
onerror has a this parameter for webworker, and doesn't allow strings as event names, nor does it have 4 trailing optional parameters. But it might be worthwhile to change it if it's the only conflict left.
With the conflicts resolved, people would be able to have both dom and webworker for their lib.
All these types are built in the types exported from Edge, so changing them would require a lot of work in TSJS-lib-generator, manually converting the webidl declarations into the JSON override format. So testing this change will be labour-intensive.
Reacted by Mike P, aar-1, Lucas Astrada, Stephen Traiforos and Seb Insua
Having just discussed this on Gitter, I realized that the general problem here isn't just about dom and webworker, despite appearances; that's just a symptom. JS is ubiquitous nowadays and I'd expect it's not uncommon to have code for a few different platforms existing within the same source tree. But you only get one tsconfig.json (for the purposes of IDE support and IntelliSense, at least), and lib is global.
I actually have a similar problem to this today with miniSphere: the vast majority of a game will use the Sphere typings, but the build script--Cellscript.js uses the Cell API, which like Web Workers vs. DOM, is generally distinct but shares a few select classes in common.
So if there were a way to use separate typings per-file or even just per-directory, that would be an elegant solution to this problem, I think, and probably wouldn't even require modifying the .d.ts files as they're currently written.
Reacted by Ian Bellomy, roman, Armin, Cecile Muller, Filipe Silva, vaindil, Jarrod Davis, Daniel Dickison, Frank Weindel, Ned Howley and 2 more
/* eslint-env worker */typeTRequest={myrequest: number;};typeTResponse={myresponse: number;};exportinterfaceIRequestWorker{postMessage: (message: TRequest)=>void;onmessage: (message: MessageEvent<TResponse>)=>void;}interfaceIResponseWorker{postMessage: (message: TResponse)=>void;onmessage: (message: MessageEvent<TRequest>)=>void;}constworker: IResponseWorker=selfasany;// Receive from the main threadworker.onmessage=({data: {myrequest}})=>{console.log(myrequest);// Send to the main threadworker.postMessage({myresponse: 222});};
main.ts
/* eslint-env browser */importtype{IRequestWorker}from"./worker.ts";constworker=newWorker(newURL("./worker.ts",import.meta.url))asIRequestWorker;// Receive from the workerworker.onmessage=({data: {myresponse}})=>{console.log(myresponse);};// Send to the workerworker.postMessage({myrequest: 111});export{};
Having just discussed this on Gitter, I realized that the general problem here isn't just about dom and webworker, despite appearances; that's just a symptom. JS is ubiquitous nowadays and I'd expect it's not uncommon to have code for a few different platforms existing within the same source tree. But you only get one tsconfig.json (for the purposes of IDE support and IntelliSense, at least), and lib is global.
I actually have a similar problem to this today with miniSphere: the vast majority of a game will use the Sphere typings, but the build script--Cellscript.js uses the Cell API, which like Web Workers vs. DOM, is generally distinct but shares a few select classes in common.
So if there were a way to use separate typings per-file or even just per-directory, that would be an elegant solution to this problem, I think, and probably wouldn't even require modifying the .d.ts files as they're currently written.
This issue also manifests its self when using test frameworks that declare globals. It makes these globals available in each file even though they are not at runtime. It also means when you use multiple test frameworks that each declare globals of the same name, you get conflicting global definitions.
Having a mechanism for specifying different types for different file patterns sounds like a good solution to me.
As a stop-gap, it would be nice if there were a library called "DOMAndWebWorker" that was the intersection of the "DOM" and "WebWorker" libraries.
But to solve the problem in general, we can see from the fact that including "DOM" and "WebWorker" in compilerOptions.lib results in an OR operation between the two libraries, that what we need is some way to do AND operations between libraries. Maybe the compilerOptions.lib property could be set as a string, something like "ESNext | (DOM & WebWorker)".
Reacted by githorse, Luis Hernandez, Russell Dempsey, Cuixiping and Frank Weindel
So I guess I'm here after 6 years just wondering if there is some workaround cause all I would like is execute my classes and functions inside the webworker but in a typescript nice way. Is there a solution for that if I have e.g. a module and then want to import things from that module inside my worker?
All posts I saw seemed to be workarounds by waiting for webpack to compile it and then grab a specific module etc.
If one file need work on both dom and web worker, how to config the compilerOptions.lib?
For example:
if(typeofimportScripts=='function'&&typeofwindow=='undefined'){// some code for web workerimportScripts('abc.js');}else{// some code for domalert(document.title);}
If one file need work on both dom and web worker, how to config the compilerOptions.lib?
The current state seems to be that there is no correct type-safe way to do this.
The only available option for module authors is to maintain two modules, one compiled for web worker and one compiled for DOM, and then a "dispatcher" module that imports both as un-typed javascript, uses a non-type-safe environment tester function to determine which one to call, and dispatches module consumer function calls to one or the other. That dispatcher module can then type itself, without referencing either "dom" or "webworker" definitions, and hide the kludge from consumers.
Reacted by Sebastian Müller, Laurent Payot and NikkiIsSleepy
Activity
DanielRosenwasser commentedon Dec 12, 2017
Unfortunately the base APIs for WebWorker and DOM are actually meaningfully different, and it's not clear at this point how to write a clean separation of global scopes between different parts of your project other than splitting your project into multiple parts.
kitsonk commentedon Dec 12, 2017
We have found that what is meaningful in the global scope of a web worker is significantly more narrow than we find out of the DOM. So we tend to author with
"lib": [ "dom" ]and then justdeclarethe handful of APIs we require to make a web worker work, or we obtain a reference to the global object, treat it asany, and pick off certain properties from the global scope and type them at the point where we pick them off.While it isn't ideal, it saves us from the only other realistic option, splitting the code. If you have modular code, and pick off parts of a global scope and type them, and you are using modular code, you should be able to author isomorphic modules fairly easily. Here is an example of the most "bullet proof" way to get a reference to the global scope, which avoids any issues with CSP:
shamhub commentedon May 18, 2018
Kitson Kelly (@kitsonk) But, do I need to write your above code in every file? and use
globalObjectfor referring propertiesHow do I handle this scenario in here?
charlesbodman commentedon May 18, 2018
Programming (@shamhub) , no, you would use the global object instead of self
That being said, in your case, you don't need the global object. If you want to get around the typing errors, you can just use
shamhub commentedon May 19, 2018
Charles Bodman (@charlesbodman) I have used second option but I get error
No webworker supportas mentioned herecharlesbodman commentedon May 20, 2018
Programming (@shamhub) , it's because you're checking for worker support inside of the worker. No need.
shamhub commentedon May 21, 2018
Charles Bodman (@charlesbodman) Yes it works now. In JS, we have
SharedWorkerobject. Am trying to execute the same code usinglet worker: SharedWorker = new SharedWorker('worker.js');but I see the errorCannot find name 'SharedWorker'mhegazy commentedon May 21, 2018
SharedWorker needs to have its own lib file. mind filing a new ticket to track creating that.
mhegazy commentedon May 22, 2018
logged #24323 to track adding
SharedWorkersupportfilipesilva commentedon Apr 18, 2019
Mohamed Hegazy (@mhegazy) Daniel Rosenwasser (@DanielRosenwasser) we're also running into the incompatible
domandwebworkertypings in Angular CLI projects and that leaves us in a tricky spot. I have described the situation in angular/angular-cli#14188 (comment).I suppose the "right" approach would be for IDE support to better approximate compilation support by supporting multiple tsconfigs on the same folder that affect different combination of files. But that sounds hard and needs to be supported by the IDE proper as well.
I'm not sure what the correct approach is right now.
DanielRosenwasser commentedon Apr 18, 2019
(Heads up, Mohamed Hegazy (@mhegazy) is no longer on the team. CCing Ryan Cavanaugh (@RyanCavanaugh))
4 remaining items
yGuy commentedon Jan 16, 2020
To add to my previous comment above: For libraries, there actually is a work around: It's also an all-or-nothing flag, so really having more control over this would be appreciated: Use the
skipLibCheckoption to disable checking of the .d.ts files that only compile cleanly in the "other" lib context.TroyAlford commentedon Feb 18, 2020
Though it is a little bit ugly, here is a method I've gotten to work:
This actually makes the intellisense work on the
postMessagecorrectly as well in VSCode, by correctly forcing recognition of the type ofself. I dislike theas unknownin the middle, but without that, I get a different TS error:If there's a cleaner syntax for this, I'd love a hint. :)
sandersn commentedon May 6, 2020
Orta Therox (@orta) and I put our heads together on this to see if Ryan Cavanaugh (@RyanCavanaugh)'s proposed solution is workable. So far, we think Yes, with some caveats that we need to investigate. Here's are some notes; we'll work more on this soon.
a. New types and values specific to webworker. We believe this is most of what people want from including webworker.
b. Missing values and types that don't make sense for webworker. eg webworker doesn't have the type HTMLOrSVGImageElement. This is nice to exclude but not the highest priority.
c. Types that conflict and values with conflicting types.
lib.browser.d.ts, would solve (a) and (b) -- just put the core things into browser and let webworker or dom respectively extend the core.browserin an unsound way.thisparameter.onerrorandself.selfis defined in the same way for both files, but webworker uses the much smaller typeWorkerGlobalScopeinstead ofWindow. If it used the nameWindowinstead it would probably merge cleanly with the DOM'sself, although I haven't tested this yet.onerrorhas athisparameter for webworker, and doesn't allow strings as event names, nor does it have 4 trailing optional parameters. But it might be worthwhile to change it if it's the only conflict left.fatcerberus commentedon Jun 12, 2020
Having just discussed this on Gitter, I realized that the general problem here isn't just about
domandwebworker, despite appearances; that's just a symptom. JS is ubiquitous nowadays and I'd expect it's not uncommon to have code for a few different platforms existing within the same source tree. But you only get onetsconfig.json(for the purposes of IDE support and IntelliSense, at least), andlibis global.I actually have a similar problem to this today with miniSphere: the vast majority of a game will use the Sphere typings, but the build script--
Cellscript.jsuses the Cell API, which like Web Workers vs. DOM, is generally distinct but shares a few select classes in common.So if there were a way to use separate typings per-file or even just per-directory, that would be an elegant solution to this problem, I think, and probably wouldn't even require modifying the
.d.tsfiles as they're currently written.cecilemuller commentedon Jan 20, 2021
In the meantime, the workaround I use is typing
selfin the worker file:You can even go further and type the messages:
worker.ts
main.ts
cameron-martin commentedon Oct 28, 2021
This issue also manifests its self when using test frameworks that declare globals. It makes these globals available in each file even though they are not at runtime. It also means when you use multiple test frameworks that each declare globals of the same name, you get conflicting global definitions.
Having a mechanism for specifying different types for different file patterns sounds like a good solution to me.
capnmidnight commentedon Nov 30, 2021
As a stop-gap, it would be nice if there were a library called "DOMAndWebWorker" that was the intersection of the "DOM" and "WebWorker" libraries.
But to solve the problem in general, we can see from the fact that including "DOM" and "WebWorker" in
compilerOptions.libresults in an OR operation between the two libraries, that what we need is some way to do AND operations between libraries. Maybe thecompilerOptions.libproperty could be set as a string, something like "ESNext | (DOM & WebWorker)".sample-system-web-app: Migrate worker files to typescript
muhamedkarajic commentedon Mar 8, 2023
So I guess I'm here after 6 years just wondering if there is some workaround cause all I would like is execute my classes and functions inside the webworker but in a typescript nice way. Is there a solution for that if I have e.g. a module and then want to import things from that module inside my worker?
All posts I saw seemed to be workarounds by waiting for webpack to compile it and then grab a specific module etc.
cuixiping commentedon Apr 12, 2023
If one file need work on both dom and web worker, how to config the compilerOptions.lib?
For example:
fix: disable reference lib=worker
MattiasMartens commentedon Oct 17, 2023
The current state seems to be that there is no correct type-safe way to do this.
The only available option for module authors is to maintain two modules, one compiled for web worker and one compiled for DOM, and then a "dispatcher" module that imports both as un-typed javascript, uses a non-type-safe environment tester function to determine which one to call, and dispatches module consumer function calls to one or the other. That dispatcher module can then type itself, without referencing either "dom" or "webworker" definitions, and hide the kludge from consumers.
chore: appease typescript for the sake of prism
feat(code-block): client-side highlighting (#1837)
release: clefairy (#1802)