webworker-typed
TypeScript icon, indicating that this package has built-in type declarations

1.0.4 • Public • Published

webworker-typed

Dead simple type-safe Web Workers.

Installation

npm install webworker-typed

Usage

Create a worker file and export the functions you want to expose:

// my-worker.ts
import { exportWorker } from 'webworker-typed';

function foo() { return 'bar'; }

async function asyncFoo() { return 'bar'; }

export default exportWorker({
  foo,
  asyncFoo,
  inline: () => 'bar',
});

From your main thread, import the worker and call the functions:

// main.ts
import { importWorker } from 'webworker-typed';
import type MyWorker from './my-worker.ts';

const untypedWorker = new Worker(new URL('./my-worker.ts', import.meta.url)); // example with webpack
const worker = importWorker<typeof MyWorker>(untypedWorker);

async (() => {
  // all imported methods are async
  console.assert(await worker.foo() === 'bar');
  console.assert(await worker.asyncFoo() === 'bar');
  console.assert(await worker.inline() === 'bar');
});

License

This project is licensed under the MIT License.

Readme

Keywords

none

Package Sidebar

Install

npm i webworker-typed

Weekly Downloads

77

Version

1.0.4

License

MIT

Unpacked Size

6.83 kB

Total Files

6

Last publish

Collaborators

  • radialapps