Back to Python
2026-02-119 min read

TS Enums (Python Programming)

Learn TS Enums (Python Programming) step by step with clear examples and exercises.

Title: TypeScript Enums in Python Programming: A full guide

Why This Matters

TypeScript enums play a crucial role in modern web development by offering several advantages over traditional JavaScript objects for defining and managing named constants, especially when working with larger codebases. Understanding how to use TypeScript enums can help you write more maintainable, efficient, and type-safe code. This knowledge is essential for interview preparation, real-world development projects, and debugging common issues in your code.

TypeScript enums offer several benefits over traditional JavaScript objects:

  1. Strong typing: TypeScript enums ensure that the values assigned to an enum member are consistent and adhere to the specified type. This can help catch errors early in the development process.
  2. Auto-generated documentation: TypeScript automatically generates documentation for your enum members, making it easier to understand the intended usage of each constant.
  3. Improved code readability: By using enums instead of raw numeric values or strings, your code becomes more self-explanatory and easier to maintain over time.
  4. Type safety: TypeScript enums enforce type safety at runtime, preventing unexpected behavior due to incorrect data types.
  5. TypeScript enums can be declared with two different types: string or number. The default type is number, but you can explicitly specify the type by adding a colon (:) and assigning the desired type to your enum. For example, if you want to create an enum of string values, you would declare it as follows:
enum Color {
Red = "red",
Green = "green",
Blue = "blue"
}

In this example, we have defined an enum called Color with three members: Red, Green, and Blue. Each member is assigned a string value.

Prerequisites

To follow this guide, you should have a basic understanding of the following concepts:

  • Python programming language syntax and data types
  • Variables, functions, and control structures (if/else, loops)
  • Basic knowledge of object-oriented programming principles
  • Familiarity with TypeScript syntax and features is beneficial but not required.

Core Concept

TypeScript enums are a way to define a set of named constants. They provide several benefits over traditional JavaScript objects:

  1. Strong typing: TypeScript enums ensure that the values assigned to an enum member are consistent and adhere to the specified type. This can help catch errors early in the development process.
  2. Auto-generated documentation: TypeScript automatically generates documentation for your enum members, making it easier to understand the intended usage of each constant.
  3. Improved code readability: By using enums instead of raw numeric values or strings, your code becomes more self-explanatory and easier to maintain over time.
  4. Type safety: TypeScript enums enforce type safety at runtime, preventing unexpected behavior due to incorrect data types.
  5. TypeScript enums can be declared with two different types: string or number. The default type is number, but you can explicitly specify the type by adding a colon (:) and assigning the desired type to your enum. For example, if you want to create an enum of string values, you would declare it as follows:
enum Color {
Red = "red",
Green = "green",
Blue = "blue"
}

In this example, we have defined an enum called Color with three members: Red, Green, and Blue. Each member is assigned a string value.

Enum Members Initialization

TypeScript enums can be initialized in two ways:

  1. Automatic initialization: If you don't explicitly assign values to your enum members, TypeScript will automatically generate sequential integer values starting from 0 for number enums or string values alphabetically sorted for string enums. However, if you want to use specific values for your enum members, make sure to assign them explicitly.
  2. Explicit initialization: You can initialize enum members by providing a value when defining the member. If you don't provide an initial value, TypeScript will automatically generate a value based on the previous member's value or default to 0 for number enums and "A" for string enums.

Enum Types

TypeScript enums can be declared with two different types: string or number. The default type is number, but you can explicitly specify the type by adding a colon (:) and assigning the desired type to your enum. For example, if you want to create an enum of string values, you would declare it as follows:

enum Color {
Red = "red",
Green = "green",
Blue = "blue"
}

In this example, we have defined an enum called Color with three members: Red, Green, and Blue. Each member is assigned a string value.

Worked Example

Let's create a simple example that demonstrates how TypeScript enums can be used in Python:

// Define an enum in TypeScript
enum Color {
Red = "red",
Green = "green",
Blue = "blue"
}

// Transpile the TypeScript code to JavaScript using tsc
tsc --init
tsc index.ts

// Include the generated JavaScript file in your Python project
import color from './index.js'

def main():
car.color = Color.Red
print(f"The car's color is {car.color}")

class Car:
def __init__(self, color):
self.color = color

car = Car(color=color.Red)
main()

In this example, we first define a TypeScript enum called Color. We then transpile the TypeScript code to JavaScript using the TypeScript compiler (tsc). After that, we include the generated JavaScript file in our Python project and create a simple Car class with a color attribute. Finally, we set the car's color to Color.Red and print it out.

Common Mistakes

  1. Forgetting to initialize enum members: If you don't explicitly assign values to your enum members, TypeScript will automatically generate sequential integer values starting from 0 for number enums or string values alphabetically sorted for string enums. However, if you want to use specific values for your enum members, make sure to assign them explicitly.
  2. Misunderstanding the default value assignment: By default, TypeScript assigns sequential integer values to enum members starting from 0 for number enums. For string enums, the order is alphabetical. If you override some of these values, it's essential to understand how the remaining values are assigned:
  • If you set the value of a member that is higher than the highest previously assigned value, the gap between the previous and new values will be filled with sequential integers or alphabetically sorted string values.
  • If you set the value of a member that is lower than the lowest previously assigned value, TypeScript will throw an error because there are no gaps to fill.
  1. Using enums in JavaScript without transpiling: To use TypeScript enums in JavaScript, you need to compile your TypeScript code using the TypeScript compiler (tsc). Make sure to include the generated JavaScript file in your project and import it correctly.
  2. Confusing enums with regular objects: While both enums and regular objects can be used to store named constants, they have different properties and behaviors. Be mindful of the advantages and limitations of each approach when deciding which one to use in a given situation.

Common Mistakes (subheading)

  1. Not handling missing enum members: If you try to access an enum member that hasn't been explicitly defined, TypeScript will throw an error. To avoid this, make sure all required enum members are defined before using them in your code.
  2. Using invalid values for enum members: TypeScript enums enforce strong typing, so if you try to assign an invalid value to an enum member, TypeScript will throw an error. Make sure to use only the valid values assigned to your enum members.
  3. Not understanding enum types: Understanding the differences between number and string enums is essential for correctly defining and using enums in TypeScript. Be aware of the default type (number) and how to explicitly specify the type (string).
  4. Ignoring auto-generated documentation: TypeScript automatically generates documentation for your enum members, making it easier to understand their intended usage. Make sure to take advantage of this feature when working with enums.

Practice Questions

  1. Define an enum called Shape with members Circle, Square, and Triangle. Assign specific string values to these members.
  2. Write a Python function that takes a Color enum as an argument and prints the name of the color.
  3. Create a class called Rectangle with attributes width and height. Add a method called area() that calculates the area of the rectangle using these attributes. Use TypeScript enums to define valid values for the Color attribute.
  4. (Bonus) Write a Python function that takes an enum as an argument, checks if it has a specific member, and returns whether or not the member exists in the enum.
  5. (Advanced) Implement a TypeScript enum with a custom serialization method to convert the enum values to integers when transpiled to JavaScript.

FAQ

  1. Can I use TypeScript enums in JavaScript without transpiling?

No, you need to compile your TypeScript code using the TypeScript compiler (tsc) before using it in a JavaScript environment.

  1. What happens if I don't initialize all enum members in TypeScript?

If you don't explicitly assign values to your enum members, TypeScript will automatically generate sequential integer values starting from 0 for number enums or string values alphabetically sorted for string enums. However, if you want to use specific values for your enum members, make sure to assign them explicitly.

  1. Can I use TypeScript enums in other programming languages besides JavaScript and TypeScript?

No, TypeScript enums are a feature specific to the TypeScript programming language. However, you can create similar constructs in other languages using classes or constants.

  1. How do I check if an enum member exists in TypeScript?

You can use the hasOwnProperty() method on the enum constructor to check if a specific member exists:

if (Color.hasOwnProperty("Red")) {
console.log("The Color enum has a Red member.");
}

FAQ (subheading)

  1. What is the default type for TypeScript enums?

The default type for TypeScript enums is number. However, you can explicitly specify the type by adding a colon (:) and assigning the desired type to your enum. For example, if you want to create an enum of string values, you would declare it as follows:

enum Color {
Red = "red",
Green = "green",
Blue = "blue"
}
  1. How does TypeScript automatically assign values to enum members?

TypeScript automatically assigns sequential integer values starting from 0 for number enums or string values alphabetically sorted for string enums if you don't explicitly assign values to your enum members. However, if you override some of these values, the remaining values will be assigned based on their order in the code.

  1. Can I use TypeScript enums with other programming languages?

TypeScript enums are a feature specific to the TypeScript programming language and cannot be directly used with other languages. However, you can create similar constructs using classes or constants in other languages.

  1. How do I check if an enum member exists in TypeScript?

You can use the hasOwnProperty() method on the enum constructor to check if a specific member exists:

if (Color.hasOwnProperty("Red")) {
console.log("The Color enum has a Red member.");
}
TS Enums (Python Programming) | Python | XQA Learn