To convert an array of strings into a string literal union type in TypeScript, you can first define the array of strings then make the array as readonly
using the as const
keyword, and then use the typeof
operator on all the values contained in the array.
TL;DR
// array of strings but in readonly mode
const namesArr = ["John", "Lily", "Roy"] as const;
// convert namesArr into string literal union type
type Names = typeof namesArr[number]; // "John" | "Lily" | "Roy"
I know, it takes some time to understand what is happening. So, Let me take you into it step by step.
First, we can initialize an array of strings like this,
// array of strings
const namesArr = ["John", "Lily", "Roy"];
Our aim is to convert this array of strings into a string literal union type
.
For that first, we have to use the as const
keyword on the array itself so that the array becomes a constant thing in every manner or readonly
mode in TypeScript.
it can be done like this,
// array of strings but in readonly mode
const namesArr = ["John", "Lily", "Roy"] as const;
After making the namesArr
array into readonly
mode, you cannot use the usual push
, pop
, slice
, etc. array methods. It is in every manner a constant.
Now we need to make this readonly array into a string literal union type.
For that let's define a type called Names
and then use the typeof
operator on all the values on the namesArr
array.
It can be done like this,
// array of strings but in readonly mode
const namesArr = ["John", "Lily", "Roy"] as const;
// convert namesArr into string literal union type
type Names = typeof namesArr[number]; // "John" | "Lily" | "Roy"
Now you may ask why are we using the number
type on the namesArr
, it is to tell the TypeScript compiler to grab all the numbered indexed values from the namesArr
array and then create a type from all its values.
So when TypeScript tries to infer the type of all values contained in the namesArr
array it will create a type of string literal union type since all the values inside the array are constant
and readonly
.
In the end, the Names
type would contain something like this,
type Names = "John" | "Lily" | "Roy";
Which is what we want. Now you can use the Names
type in TypeScript.
See the above code live in codesandbox