Generic class syntax
📖 Scenario: Imagine you want to create a box that can hold any type of item. This box should be able to store numbers, strings, or even objects. Using a generic class helps you build such a flexible box.
🎯 Goal: You will build a generic class called Box that can store one item of any type. Then, you will create a box for numbers and a box for strings, and finally print their contents.
📋 What You'll Learn
Create a generic class called
Box with a type parameter T.Add a property
content of type T to the class.Add a constructor that takes a parameter
content of type T and assigns it to the property.Create a variable
numberBox of type Box<number> with content 123.Create a variable
stringBox of type Box<string> with content 'hello'.Print the contents of
numberBox and stringBox.💡 Why This Matters
🌍 Real World
Generic classes let you write flexible and reusable code that works with many data types without repeating yourself.
💼 Career
Understanding generics is important for writing clean, type-safe code in TypeScript, which is widely used in web development jobs.
Progress0 / 4 steps