Reputation: 3012
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?
Upvotes: 2
Views: 65
Reputation: 1075337
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";
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... :-) )
Upvotes: 1