An enum in TypeScript is a way to define a set of named constants. It allows you to create a collection of related values that can be referred to by their names. Enums can be numeric or string - based.
Here is a simple numeric enum example:
enum Direction {
Up,
Down,
Left,
Right
}
console.log(Direction.Up); // Output: 0
In this example, the Direction
enum has four members. By default, the first member has a value of 0, and subsequent members have values incremented by 1.
You can also create a string - based enum:
enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE"
}
console.log(Color.Red); // Output: "RED"
Constants in TypeScript are variables that are declared using the const
keyword. Once a constant is assigned a value, it cannot be reassigned. Constants are used to store values that should not change throughout the execution of the program.
const PI = 3.14159;
// PI = 3; // This will cause a compilation error
Enums are used when you want to group related values together and give them meaningful names. You can use enums in conditional statements, function parameters, and return types.
enum Response {
No = 0,
Yes = 1
}
function respond(answer: Response) {
if (answer === Response.Yes) {
console.log('You answered yes.');
} else {
console.log('You answered no.');
}
}
respond(Response.Yes); // Output: You answered yes.
Constants are used to store single values that should remain unchanged. They can be used in calculations, as default values for functions, or in any place where a fixed value is required.
const MAX_USERS = 100;
function checkUserLimit(usersCount: number) {
if (usersCount > MAX_USERS) {
console.log('User limit exceeded.');
} else {
console.log('Within user limit.');
}
}
checkUserLimit(120); // Output: User limit exceeded.
enum Month {
January,
February,
March,
//... other months
}
function getMonthName(month: Month) {
// Function implementation
}
// getMonthName(100); // This will cause a compilation error
PI
or application - specific limits.const API_URL = 'https://example.com/api';
const TIMEOUT = 5000;
Enums and constants are both valuable tools in TypeScript, but they serve different purposes. Enums are ideal for grouping related values and providing type safety, while constants are used for storing single, unchanging values. By understanding their differences and following the best practices, developers can write more robust, readable, and maintainable TypeScript code.