Home > Mobile >  Narrowing of string - count of values
Narrowing of string - count of values

Time:10-26

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)

CodePudding user response:

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.

  • Related