13. Enums & Generics (Key Concept)
Next-Level Abstractions
As your application logic gets more complex, writing literal types for every scenario can become repetitive. Furthermore, you will eventually need to write functions that are flexible enough to accept any type of data, while still maintaining strict safety. This module covers Enums for organization, and Generics—the most important intermediate concept in TypeScript.
Enums: Named Constants
An enum (short for enumeration) allows you to define a set of named constants. Unlike Types or Interfaces, which are completely erased during compilation, Enums actually generate real JavaScript code (objects) that you can interact with at runtime.
String Enums
Numerical enums can be confusing when debugging because you just see the number 1 instead of "Error" in your logs. It is highly recommended to use String Enums instead.
Generics: The Type Variables (KEY CONCEPT)
Imagine you want to write a function that takes an argument and just returns it. If you type it as `number`, it only works for numbers. If you type it as `any`, you lose all TypeScript safety.
Generics act as a variable for the type itself. They capture the type of the data you pass in, and lock it in for the rest of the function execution.
Generics in Interfaces
Generics aren't just for functions. They are heavily used in Interfaces to create flexible, reusable blueprints, especially for API responses where the shape of the data changes, but the overall structure (status, errors) remains the same.
Knowledge Check
Ready to test your understanding of 13. Enums & Generics (Key Concept)?