Recall & Review
beginner
What is a generic interface in TypeScript?
A generic interface is a way to define an interface with a placeholder type that can be specified later. It allows the interface to work with any data type while keeping type safety.
Click to reveal answer
beginner
How do you declare a generic interface for a collection of items in TypeScript?
You declare it using angle brackets with a type parameter, for example:
interface Collection<T> { add(item: T): void; get(index: number): T; } where T is the generic type.Click to reveal answer
beginner
Why use a generic interface for collections instead of a specific type?
Using a generic interface lets you reuse the same code for different types of collections, like numbers, strings, or custom objects, without losing type safety or writing duplicate code.
Click to reveal answer
beginner
Example: What does this interface mean? <br>
interface Collection<T> { add(item: T): void; get(index: number): T; }It means the Collection interface works with any type
T. It has an add method to add an item of type T, and a get method to get an item of type T by index.Click to reveal answer
beginner
How do you create a collection of strings using the generic interface
Collection<T>?You specify the type when using the interface, like <code>let stringCollection: Collection<string></code>. This means the collection will only hold strings.Click to reveal answer
What does the
T represent in interface Collection<T>?✗ Incorrect
T is a placeholder that stands for any type you want to use when you create a collection.
How do you specify the type when using a generic interface?
✗ Incorrect
You specify the type by putting it inside <> after the interface name, like Collection<number>.
Which of these is a benefit of using generic interfaces for collections?
✗ Incorrect
Generic interfaces let you reuse the same code for many types while keeping type safety.
If you have
let numbers: Collection<number>, what type of items can you add?✗ Incorrect
The collection is set to hold numbers only, so you can add only numbers.
What happens if you try to add a string to
Collection<number>?✗ Incorrect
TypeScript will show a type error because the collection expects numbers only.
Explain what a generic interface for collections is and why it is useful.
Think about how you can write one interface that works for many types.
You got /4 concepts.
Describe how you would create and use a generic collection interface to store strings.
Focus on how to tell TypeScript the collection holds strings.
You got /4 concepts.