Generic interface for collections
📖 Scenario: You are building a simple program to manage collections of items. You want to create a generic interface that can work with any type of collection, like numbers or strings.
🎯 Goal: Create a generic interface called Collection with a method to add items and a method to get all items. Then use this interface with a number collection and a string collection.
📋 What You'll Learn
Create a generic interface called
Collection with a type parameter T.Add a method
add(item: T): void to add an item to the collection.Add a method
getAll(): T[] to return all items in the collection.Create a variable
numberCollection of type Collection<number>.Create a variable
stringCollection of type Collection<string>.💡 Why This Matters
🌍 Real World
Generic interfaces help you write flexible code that works with many types of data, like lists of numbers, strings, or custom objects.
💼 Career
Understanding generics is important for TypeScript developers to create reusable and type-safe components and libraries.
Progress0 / 4 steps