Typescript string literals from array of strings
We can create a type of string literals that comes from an array if we add the as const
modifier to the array. This way:
const COLORS = ["red", "blue", "green"] as const;
type Color = typeof COLORS[number];
This way the type Color
will be inferred as either "red"
, "blue"
or "green"
. If you remove the as const
then the type Color
will be a string
.