0
0
Typescriptprogramming~5 mins

Generic class syntax in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a generic class in TypeScript?
A generic class is a class that can work with any data type, specified when creating an instance. It uses a placeholder type (like <T>) to allow flexibility.
Click to reveal answer
beginner
How do you declare a generic class in TypeScript?
You add a type parameter in angle brackets after the class name, for example: <code>class Box&lt;T&gt; { ... }</code> where <code>T</code> is the placeholder type.
Click to reveal answer
beginner
What does T represent in a generic class?
T is a type parameter that acts like a variable for a type. It gets replaced by a real type when you create an instance of the class.
Click to reveal answer
beginner
How do you create an instance of a generic class with a specific type?
You specify the type inside angle brackets when creating the object, like <code>let box = new Box&lt;string&gt;();</code> to make <code>T</code> equal to <code>string</code>.
Click to reveal answer
beginner
Why use generic classes instead of regular classes?
Generic classes let you write flexible and reusable code that works with many types without repeating the same class for each type.
Click to reveal answer
How do you declare a generic class named Container with a type parameter?
Aclass Container {}
Bclass Container<T> {}
Cclass Container<T>[] {}
Dclass Container[] {}
What does the T in class Box<T> represent?
AA function
BA specific type like string
CA variable name
DA placeholder for any type
How do you create an instance of Box for numbers?
Alet box = new Box<number>();
Blet box = new Box();
Clet box = new Box<string>();
Dlet box = Box<number>;
Why are generic classes useful?
AThey allow code reuse with different types
BThey only work with strings
CThey make code slower
DThey replace functions
Which of these is NOT a correct way to declare a generic class?
Aclass Data<T, U> {}
Bclass Data<U> {}
Cclass Data[] {}
Dclass Data<T> {}
Explain how to declare and use a generic class in TypeScript.
Think about how you tell the class what type it should work with.
You got /3 concepts.
    Why would you choose a generic class over a normal class?
    Consider how you can write one class that fits many needs.
    You got /3 concepts.