Difference Between Enum and Type in Typescript

1. Introduction

In TypeScript, enum and type are two constructs that allow you to define named constants and type aliases, respectively. An enum (short for enumeration) is a way to group a set of related values under a single name, typically used to represent a fixed set of options. A type, on the other hand, is used to create type aliases - custom names for type annotations, which can be simple or complex types.

2. Key Points

1. Purpose: enum is for named constant values, and type is for creating type aliases.

2. Usage: enum defines a set of named constants, type can define a new name for any type including primitives, unions, and intersections.

3. Mutability: Enums are immutable by default, while type aliases are just aliases and don’t imply immutability.

4. Runtime vs Compile Time: Enums exist at runtime and compile time, and types exist only at compile time.

3. Differences

Characteristic Enum Type
Purpose Named constant values Type aliases
Usage Fixed set of options Any type, including unions, primitives, etc.
Mutability Immutable Just aliases, don’t imply immutability
Runtime vs Compile Time Both runtime and compile time Only compile time

4. Example

// Example of Enum
enum Color {
    Red,
    Green,
    Blue
}

// Example of Type
type Point = {
    x: number;
    y: number;
};

Output:

No direct output as these are structural examples.

Explanation:

1. The Color enum creates a fixed set of options for colors.

2. The Point type alias defines a shape for an object with x and y coordinates.

5. When to use?

- Use enum when you need a group of related constants that have a fixed set of values, like days of the week, directions, or user roles.

- Use type when you want to create a custom type definition or alias, such as for complex object structures, or to simplify complex type annotations with a single name.

Comments