0
0
Typescriptprogramming~5 mins

Generic interface for collections in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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&lt;string&gt;</code>. This means the collection will only hold strings.
Click to reveal answer
What does the T represent in interface Collection<T>?
AA function name
BA specific type like string
CA placeholder for any type
DA variable name
How do you specify the type when using a generic interface?
ABy writing the type inside angle brackets after the interface name
BBy writing the type before the interface name
CBy using a special keyword 'type'
DYou cannot specify the type
Which of these is a benefit of using generic interfaces for collections?
AReuse code for different data types safely
BMake code run faster
CAvoid using any types
DAutomatically convert types
If you have let numbers: Collection<number>, what type of items can you add?
AOnly strings
BOnly numbers
CAny type
DOnly objects
What happens if you try to add a string to Collection<number>?
AThe program crashes
BIt works fine
CThe string is converted to number automatically
DTypeScript shows an error
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.