Today I Learned

hashrocket A Hashrocket project

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.

See More #javascript TILs
Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.