Typescript support for variants

Currently variant in typescript looks like this:

type MyVariant = { "ok" : string } | { "err" : string  }

It is hard to use type predicates.

I think it would be great to have following:

type Type_1 = { "ok" : string }
type Type_2 = { "err" : string }
type MyVariant = Type_1 | Type_2

Now we can use type predicates:

function isType1(value: Type_1 | Type_2): value is Type_1 {
    return (value as Type_1).hasOwnProperty("ok");
}

function isType2(value: Type_1 | Type_2): value is Type_2 {
    return (value as Type_2).hasOwnProperty("err");
}

What gives us:

function myFunc(a: MyVariant) {
    if (isType1(a)) {
        let err = a.err;//TS2339: Property 'err' does not exist on type 'Type_1'.
        let ok = a.ok;
    } else if (isType2(a)) {
        let err = a.err;
        let ok = a.ok;//TS2339: Property 'ok' does not exist on type 'Type_2'.
    }
}

Profit!

@kpeacock Please tag someone who can help

Thanks!

2 Likes

@chenyan @claudio we’ve discussed this before internally, but here’s some community feedback

1 Like

@kpeacock, are there any improvements in the roadmap?
Thanks in advance

I don’t know typescript well, but does the following work?

function myFunc(a: MyVariant) {
  if (a.hasOwnProperty("ok")) {
    let ok = a.ok;
  } else if (a.hasOwnProperty("err")) {
    let err = a.err;
  }
}