0

If I have a type

type SomeType = 'a' | 'b' | 'c'

is there any typescript function that will return count of different values a variable of type SomeType can have:

assertEq(someFn(SomeType), 3)
DraganS
  • 2,621
  • 1
  • 27
  • 40
  • 1
    If you have a union type and you want to create a tuple representation which should depend on the union you can take a look on this answer https://stackoverflow.com/questions/69676439/create-constant-array-type-from-an-object-type/69676731#69676731 – captain-yossarian from Ukraine Oct 25 '21 at 12:15
  • Thanks for a tip. In this case I had to have something that works like an enum so the Cerbrus's approach is a perfect match for my "problem" – DraganS Oct 25 '21 at 12:18
  • you don't need an enum. `TupleUnion<'a' | 'b' | 'c'>` --> `['a','b','c'] | ['b','a','c'] | ....` – captain-yossarian from Ukraine Oct 25 '21 at 12:19

1 Answers1

1

Typescript types only exist in your IDE / compiler. They're not actually there, when you run your code.

This means that you can't access the type / iterate over it.

An alternative could be to use a const array, and extract an type from that:

const Types = ['a', 'b', 'c'] as const;
type SomeType = typeof Types[number];

Then you can just use Types.length in your test.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147