Skip to content

v0.11.0: Better Unions

Compare
Choose a tag to compare
@rrdelaney rrdelaney released this 28 Aug 16:40
· 143 commits to master since this release

Simpler & Inlined Union Types

It's pretty common in JS to use the following pattern:

declare function add(a: string | number, b: string | number): string

Before this release we would generate a helper type for the union, which was eliminated at runtime. Since then BuckleScript released @bs.unwrap, allowing us to produce the following output:

external add :
  a::[ | `String string | `Number float] [@bs.unwrap] =>
  b::[ | `String string | `Number float] [@bs.unwrap] =>
  string =
  "" [@@bs.module "module"];

And the callsite comes pretty naturally! It looks like:

let result = add (`String "hello") (`Number 3.);

Unions of string literals also get processed as @bs.string now, making them typesafe (tm):

declare function apply(input: 'add' | 'subtract'): number
external apply :
  input::([`add | `subtract] [@bs.string]) =>
  float =
  "" [@@bs.module "module"];

Union declarations will also get inlined too!

With the input:

declare module 'module' {
  declare type input = number | string
  declare function apply(input: input): number
}

You'll get something like:

external apply :
  input::([`Number float | `String string] [@bs.unwrap]) =>
  float =
  "" [@@bs.module "module"];

This should make the API's for a lot more JS libraries easier to use and closer to what JS users would expect.

Changes