title: Structuring a TypeScript project with workers
body: <p>How should I structure a project that includes main thread (DOM) script, and workers? Eg:</p>
  
  <h1>main.ts</h1>
  
  <pre><code>// This file must have DOM types, but not worker types.
  
  const worker = new Worker('worker.js');
  
  worker.onmessage = (event) =&gt; {
    // Ideally, I should be able to reference types from the worker:
    const data = event.data as import('./worker').HelloMessage;
    console.log(data.hello);
  };
  </code></pre>
  
  <h1>worker.ts</h1>
  
  <pre><code>// This file must have worker types, but not DOM types.
  // The global object must be one of the worker globals (how do I pick which?)
  
  const helloMessage = {
    hello: 'world',
  };
  
  export type HelloMessage = typeof helloMessage;
  
  postMessage(helloMessage);
  </code></pre>
  
  <p>Whenever I've tried this in the past I feel like I've been fighting TypeScript by either:</p>
  
  <ul>
  <li>Using one <code>tsconfig.json</code> that has both worker &amp; DOM types. But of course this isn't accurate type-wise.</li>
  <li>Using multiple <code>tsconfig.json</code>. But then the project boundary makes it hard to reference types between them.</li>
  </ul>
  
  <p>Additionally, how do I declare the global in a worker? Previously I've used <code>declare var self: DedicatedWorkerGlobalScope</code>, but is there a way to actually set the global (rather than just setting <code>self</code>)?</p>