Union of literal types from an array of strings
Hi I'm looking for a way to generate a union type for every string in an array.
Let's say I have an array
const sample = ["apple", "banana", "grape", "orange""]
. Basically I want to be able to get type SomeType = "apple" | "banana" | "grape" | "orange"
. I need this SomeType
because I need to create a function that accepts one of these values instead of typing them one by one like this
As you can see it'll be a lot of work to do the typing if the number of items in the array keeps increasing (let's say like 100 items). I just want a union type that consists of the literal types of whatever strings that are in the array (in this case sample
). How can I do this in typescript?2 Replies
you can do a typecheck and confirm the type is of one of the accepted strings
a basic check to hopefully get you started would be
this is just going to make TS accept that the value is a string if it passes the test
you can construct that using the list of accepted values which is stored somewhere and iterate over the list to in an array to check if
array.includes(value)
I believe the common example floating around is also using const
Yes this is the one that I found which is close
It's just that I want
Fruits
to not be just a single item from the array (by specifying it) but instead it'll be the literal union of every value/item within the array
I can't seem to find anything about it