0
0
Typescriptprogramming~20 mins

Generic interface for collections in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Create the generic interface
Create a generic interface called Collection with a type parameter T. Inside it, declare a method add(item: T): void and a method getAll(): T[].
Typescript
Need a hint?

Use interface Collection<T> to create a generic interface with type parameter T.

2
Create number and string collections
Create a variable called numberCollection of type Collection<number> and a variable called stringCollection of type Collection<string>. For now, assign them empty objects {}.
Typescript
Need a hint?

Use const numberCollection: Collection<number> = {} and similarly for strings.

3
Implement the collections with arrays
Implement numberCollection and stringCollection as objects with an internal array called items. Add the add(item: T): void method to push items to the array, and the getAll(): T[] method to return the array.
Typescript
Need a hint?

Use an array property items inside each object to store the collection items.

4
Add items and print collections
Add the numbers 10 and 20 to numberCollection using add. Add the strings "apple" and "banana" to stringCollection using add. Then print the results of getAll() for both collections using console.log.
Typescript
Need a hint?

Use numberCollection.add(10) and console.log(numberCollection.getAll()) to add and print.