To confirm the data type of an element within myStrings
, it is essential to declare myStrings
using as const
in TypeScript to signify its immutability:
const myStrings = ["one", "two", "three"] as const;
type MyStringsElement = typeof myStrings[number]; // For easier reference
const newString: MyStringsElement = "two";
Take a look at the example on playground
Considering the values provided in myStrings
, the type of newString
will be a combination of string literals:
"one" | "two" | "three"
. This implies that only constants like
"one"
,
"two'
, or
"three"
can be assigned to
newString
(as constant values during compilation).
(Please take note: When utilizing typeof myStrings[number]
, TypeScript interprets it as (typeof myStrings)[number]
.)