To convert an array of strings to a read-only array of string literals in TypeScript, you can use a combination of TypeScript's as const
assertion and the ReadonlyArray
type. Here's how you can do it:
typescript// Input array of strings
const arrayOfStrings = ['foo', 'bar', 'baz'];
// Convert to a read-only array of string literals using 'as const' and 'ReadonlyArray'
const readonlyArrayOfLiterals = arrayOfStrings as const;
// Test
function printLiterals(arr: readonly ['foo', 'bar', 'baz']) {
console.log(arr[0]); // 'foo'
console.log(arr[1]); // 'bar'
console.log(arr[2]); // 'baz'
}
printLiterals(readonlyArrayOfLiterals);
In the example above, we first define the input array arrayOfStrings
, containing strings 'foo', 'bar', and 'baz'. We then convert this array to a read-only array of string literals using the as const
assertion. The readonlyArrayOfLiterals
will have the type readonly ['foo', 'bar', 'baz']
.
Note that the elements in the readonlyArrayOfLiterals
are now of string literal types ('foo', 'bar', 'baz') instead of the general string
type. This means that you cannot modify the elements in the readonlyArrayOfLiterals
, making it read-only. The resulting read-only array of literals can only be used with values that strictly match the literal types ('foo', 'bar', 'baz').