Generic Stack Implementation

easyTypeScript

Lesson

Understanding Generic Classes and Type Safety

Generic classes in TypeScript allow you to create reusable components that work with multiple types while maintaining type safety. When you add a generic type parameter to a class, you're essentially creating a template that can be specialized for different types.

The key benefit of generics is type safety without sacrificing flexibility. Instead of using any (which loses all type checking) or creating separate classes for each type, generics let you write one class that works correctly with any type you specify.

When you declare a generic class, you use angle brackets <T> after the class name. The T is a convention meaning "Type" - it's a placeholder that gets replaced with the actual type when you create an instance. You can use any name you want (like <ItemType> or <U>), but T is the most common.

Inside the class, you can use T anywhere you would normally specify a type - for method parameters, return types, and property types. TypeScript will ensure that all operations are type-safe based on the concrete type provided when the class is instantiated.

The magic happens at compile time: TypeScript checks that you're using the generic type consistently throughout your class, and when someone creates an instance like new Container<string>(), it verifies that all operations work correctly with strings.

Example
1class Container<T> { 2 private value: T; 3 4 constructor(initialValue: T) { 5 this.value = initialValue; 6 } 7 8 getValue(): T { 9 return this.value; 10 } 11 12 setValue(newValue: T): void { 13 this.value = newValue; 14 } 15} 16 17// Usage with different types 18const numberContainer = new Container<number>(42); 19const stringContainer = new Container<string>("hello"); 20 21// TypeScript ensures type safety 22numberContainer.setValue(100); // ✓ Valid 23// numberContainer.setValue("text"); // ✗ Type error!
L1The <T> makes this class generic - T will be replaced with the actual type
L2Private properties can use the generic type T
L9Return types use T to maintain type safety
L16When creating instances, specify the concrete type in angle brackets

Key Takeaways

  • •Generic classes use <T> to create type-safe templates that work with multiple types
  • •The generic type parameter can be used for properties, parameters, and return types throughout the class
  • •TypeScript provides full type checking and IntelliSense support based on the concrete type specified
Loading...