Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How should I handle optional exposed methods in TypeScript? #597

Open
vicary opened this issue Sep 12, 2022 · 0 comments
Open

How should I handle optional exposed methods in TypeScript? #597

vicary opened this issue Sep 12, 2022 · 0 comments

Comments

@vicary
Copy link

vicary commented Sep 12, 2022

I would like to expose a common interface for all my workers like this:

export interface WrappedWorker {
  foo?: () => void;
}

And one of my workers implements it like this:

import * as Comlink from "comlink";
import type { WrappedWorker } from "./WrappedWorker.ts";

export class FooWorker implements WrappedWorker {
  foo: () => "bar"
}

Comlink.expose(new FooWorker());

In my main thread, the wrapped worker will expose foo as Remote<() => string> | Promise<undefined>, this causes two problems:

  1. await fooWorker?.foo(); causes lint error for when foo is Promise<undefined>.
  2. If I resolve the method getter promise before actually calling, comlink proxy will try to .apply() to undefined and throws. Option 1 throws this one too if foo is actually undefined at runtime.
const worker = new Worker("./WrappedWorker.ts");
const fooWorker = Comlink.wrap(worker);

// 1. Not all constituents of type 'Promise<undefined> | Remote<() => Promisable<void>>' are callable.
await fooWorker?.foo();

// 2. TypeError: Cannot read properties of undefined (reading 'apply')
const fooMethod = await fooWorker.foo;
await fooMethod?.();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant