2

I have a type definition, imported from a different npm package, that consists of over 100 strings in union, like this:

type SomeType = "a" | "b" | "c" \\ | ... and it goes and goes

I would like to check in my code if a string variable belongs to this SomeType. Is there a way to do that which does not require me writing helper functions listing all the possible values (as described here for instance)?

In my case, listing all the values might not be the best, as the type values from that npm package may change in the future and because there is a load of them. I'm looking for some smarter way, if it exists.

scpommiifi
  • 21
  • 3

1 Answers1

0

One of typescript goals is to performs a fully type erasure on javascript ouput.

Actually (typescript v3.8) the union of literal types like:

type SomeType = "a" | "b" | "c";

are not converted into runtime values of some sort.

If implemented the proposal of spread operator on Union types will fill this gap.

In the meantime, as already suggested into the aformentioned issue, this is a nice suggestion:

Asking this 3rd party to change their library so that those union types are expressed as enums would solve this as enums generate a double mapped dictionary at runtime.

// type SomeType = "a" | "b" | "c";
enum SomeType {
  a,
  b,
  c,
}

let my_string = "a";
let isOk = SomeType.hasOwnProperty(my_string);

my_string = "z";
let isNotOk = SomeType.hasOwnProperty(my_string);
attdona
  • 17,196
  • 7
  • 49
  • 60