
String Enums vs. Numeric Enums
The enums we have studied so far are referred to as numeric enums, since they are based on numbers. TypeScript also allows us to use enums based on strings, referred to as string enums. They are defined very similarly:
enum DirectionNumber {
North,
South,
East,
West,
}
enum DirectionString {
North = 'NORTH',
South = 'SOUTH',
East = 'EAST',
West = 'WEST',
}
With numeric enums, the numbers could be assigned automatically, but with string enums we must write the string explicitly, as shown above. Technically, any string will do: North = 'JabberWocky' is a valid value definition. However, it is much better to use the convention shown here (North = 'NORTH'), where the string value of the enum variable is just the capitalized form of the variable name. This way, error messages and logs will be much more informative.
We recommend to always use string enums because numeric enums allow for some behaviors that can let bugs sneak into our code. For example, numbers can be assigned directly to numeric enum variables:
let whichWayToAntarctica: DirectionNumber
whichWayToAntarctica = 1 // Valid TypeScript code.
whichWayToAntarctica = DirectionNumber.South // Valid, equivalent to the above line.
Strangely, even assigning arbitrary numbers, as in whichWayToAntarctica = 943205, will not lead to type errors. String enums are much more strict. With string enums, variables cannot be assigned to strings at all!
let whichWayToAntarctica: DirectionString
whichWayToAntarctica = ' (•◡•) / Arbitrary String (•◡•) /' // Type error!
whichWayToAntarctica = 'SOUTH' // STILL a type error!
whichWayToAntarctica = DirectionString.South // The only allowable way to do this.
Related articles
10 Essential Steps for Migrating Your JavaScript Project to TypeScript in 2025
Discover the practical roadmap to seamlessly transition your JavaScript projects to TypeScript, enhancing type safety and developer productivity in 2025.
Crafting Dynamic Data-Driven User Interfaces with React and TypeScript
Learn how to effortlessly craft dynamic, data-driven user interfaces using React and TypeScript, enhancing your app's responsiveness and user experience.
Mastering Next-Gen API Security: JWTs with Node.js & TypeScript in 2025
Learn step-by-step how to enhance your API’s security using JWTs with Node.js and TypeScript, preparing your applications for the security demands of 2025.