enum in TypeScript

An enum (short for enumeration) is a special data type in TypeScript that allows you to define a set of named constants.

It makes the code more readable and easier to manage when dealing with fixed sets of related values.

Defining an Enum

enum Direction {
	  North,
	  South,
	  East,
	  West
}

By default, enums start numbering from 0.

Using Enums

let move: Direction = Direction.North;
console.log(move); // Output: 0

Custom Enum Values

You can assign custom values to enum members.

enum Status {
  Success = 1,
  Error = -1,
  Pending = 0
}

let result: Status = Status.Success;
console.log(result); // Output: 1

String Enums

Enums can also have string values.

enum Color {
  Red = "RED",
  Green = "GREEN",
  Blue = "BLUE"
}

let favColor: Color = Color.Green;
console.log(favColor); // Output: "GREEN"

Type Inference and Type Safety Example

const result = (
  name: "Sanket",
  marks: 98
)

The type of the above raw object is inferred as:

{
  name: string;
  marks: number;
}

Something like the given object below: