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
const aFunction = (text: "apple" | "banana" | "grape" | "orange") => {
// do something with text
}
const aFunction = (text: "apple" | "banana" | "grape" | "orange") => {
// do something with text
}
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
Coder_Carl
Coder_Carl10mo ago
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)
function isString(value): value is string {
return typeof value === "string";
}
function isString(value): value is string {
return typeof value === "string";
}
I believe the common example floating around is also using const
const fruits = ["Apple", "Orange", "Pear"] as const;
type Fruits = typeof fruits[number]
const fruits = ["Apple", "Orange", "Pear"] as const;
type Fruits = typeof fruits[number]
Sinc02
Sinc0210mo ago
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
Want results from more Discord servers?
Add your server