#Get number of options in union type

1 messages · Page 1 of 1 (latest)

meager crane
#

If I have a type, let say it looks something like that:

type Test = 'hello' | 'world' | 'test' | 'something'

How I can get the amount of the possible strings? (4)

pseudo oar
#

not possible to do it easily

#

tho you could do it by having a counter and increment it every time, and removing a member of the union, until there is nothing left

#

maybe using ts-toolbelt union -> list -> length

#
import { Union, List } from "ts-toolbelt";

type UnionLength<T> = List.Length<Union.ListOf<T>>;
foggy sable
#

@meager crane Realistically, define an array and generate the union from it:

const allTestValues = ['hello', 'world', 'test', 'something'] as const;
type Test = (typeof allTestValues)[number];
#

Unless you really do want the length as a type; but it seems more likely that you want the value at runtime.