0

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

This is a big help, thanks! This raises one more question for me though, if you have time. The union type gets consumed by a generic function type func<T extends keyof Entity> = (entity: Pick<Entity, T>) => void. Is there a way to use ArrayMember inside the function type?
You could use that ArrayMember member all over the place, including in a function type. But, your posted example doesn't have any arrays, so I have no idea where you would use it in that. That is probably a separate question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.