Home > Blockchain >  helper utility type to get union from const string array
helper utility type to get union from const string array

Time:08-03

I have string arrays that I construct with const assertions then use them to create union types.

const keys = ["foo", "bar", "moo"] as const;
type keysUnion = typeof keys[number]; // type keysUnion = "foo" | "bar" | "moo"

Is there a way to make a utility type that does the same thing with having to type typeof and [number] each time? Asking because I use this pattern multiple times so would be nice to make it more succinct.

CodePudding user response:

You cannot remove the typeof here, since you cannot use a value in a type. You must use the typeof that value when using the type of that value in a another type.


That said you could have a type like:

type ArrayMember<T extends readonly unknown[]> = T[number]

And use it like:

const keys = ["foo", "bar", "moo"] as const;
type KeysUnion = ArrayMember<typeof keys> // "foo" | "bar" | "moo"

type MyKey = ArrayMember<string[]> // string

It's not much shorter, but it does read more nicely than MyArrType[number].

Playground

  • Related