johnny-quesada-developer / easy-web-worker

This is a library to easily handle and create web-workers, if you are a web developer and never tried this... do not wait any longer! Workers are an amazing option to improve user experience and make your webpages even greater
MIT License
18 stars 1 forks source link

Fix type signatures to prevent issues with union types and Distributive Conditional Types, add support for `transfer` parameter of `postMessage` #7

Closed gabrielecirulli closed 10 months ago

gabrielecirulli commented 10 months ago

Replaces #5.

This PR fixes issues when using conditional types as TPayload and TResult such as the following type:

type MyPayload = {
  type: "first",
  foo: number,
} | {
  type: "second",
  bar: string
};

This kind of type is useful when passing messages because it lets you define a different structure for each type of message and keep them "strongly" typed.

The original typings weren't working due to TypeScript's Distributive Conditional Types. When passing a union type into A extends B ? Foo : Bar, the conditional type will be applied to each member of that union.

It appears that the solution to this is to wrap the parameters of extends into a tuple in order to circumvent the distributive nature of the conditional.

Fixes https://github.com/johnny-quesada-developer/easy-web-worker/issues/6

gabrielecirulli commented 10 months ago

Thank you!