0

I have a union type made of string literals in a third party types definition:

type Alphabet = "a" | "b" | "c"

Now I would like to know if a string is of the given type:

const letterCandidate = "b"
// doesn't work: Alphabet.includes(letterCandidate)

One way to achieve that would be to make a string array out of the type:

// somehow get to: const arr: string[] = ["a", "b", "c"]
// then could: arr.includes(letterCandidate)

Is there any way to create some kind of iterable out of the Alphabet type? Or some other solution to the problem?

Cel
  • 6,467
  • 8
  • 75
  • 110
  • 3
    Types are erased at runtime: so this feels like an XY problem. You should be defining the array, and then inferring the union type from the array values instead. – Terry May 31 '22 at 20:02
  • 2
    you can only convert it [the other way around](https://tsplay.dev/mb0XBw) – Tobias S. May 31 '22 at 20:03
  • Does this answer your question? [Typescript derive union type from tuple/array values](https://stackoverflow.com/questions/45251664/typescript-derive-union-type-from-tuple-array-values) – Terry May 31 '22 at 20:04
  • I see, the problem is I don't have write access to the third party library that defines the type. So I need to communicate to them to export an array from which to create the type, not just the type. – Cel May 31 '22 at 20:13

0 Answers0