'Typescript: How can I cast a variable as an element of an array?

Array:

const myStrings = ["one", "two", "three"];
const newString = "two";

newString will simply be of type string, but I want the type to be something like element of myStrings.

How can I do this if the values in the array may or may not change?



Solution 1:[1]

You can use typeof myStrings[number], but only if myStrings has as const telling TypeScript that its contents don't change:

const myStrings = ["one", "two", "three"] as const;
type MyStringsElement = typeof myStrings[number]; // For convenience
const newString: MyStringsElement = "two";

Playground example

With the myStrings contents you've shown, the type of newString will be "one" | "two" | "three". That's a union of three string literal types, meaning that the only valid values for newString are "one", "two', or "three" (as compile-time constant values).

(Note: typeof myStrings[number] is evaluated by TypeScript as (typeof myStrings)[number], which may be surprising. I used to think I needed the parentheses, and I'm not sure it's not best to have them for clarity even if they aren't needed... :-) )

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1