A generic class is a class that can work with any data type specified when creating an instance. It uses type parameters to allow flexibility while keeping type safety.
Click to reveal answer
intermediate
What does it mean to add constraints to a generic class?
Adding constraints means limiting the types that can be used with the generic class. This is done using the extends keyword to require the type to have certain properties or methods.
Click to reveal answer
intermediate
How do you declare a generic class with a constraint that the type must have a <code>length</code> property?
You declare it like this: <pre>class MyClass<T extends { length: number }> { /* ... */ }</pre> This means <code>T</code> must have a <code>length</code> property of type <code>number</code>.
Click to reveal answer
intermediate
Why use constraints in generic classes?
Constraints let you safely use properties or methods of the generic type inside the class, because you know those members exist. This prevents errors and improves code reliability.
Click to reveal answer
beginner
Example: What will this code print?<br><pre>class Box<T extends { name: string }> {<br> constructor(public content: T) {}<br> printName() {<br> console.log(this.content.name);<br> }<br>}<br>const box = new Box({ name: 'Apple' });<br>box.printName();</pre>
It will print Apple because the content object has a name property with the value 'Apple'. The constraint ensures T has a name string.
Click to reveal answer
What keyword is used to add constraints to a generic type in TypeScript?
Aconstrains
Bimplements
Cextends
Drestricts
✗ Incorrect
The extends keyword is used to specify constraints on generic types in TypeScript.
Which of these is a valid generic class declaration with a constraint?
Aclass Data<T requires { id: number }> {}
Bclass Data<T extends { id: number }> {}
Cclass Data<T implements { id: number }> {}
Dclass Data<T restricts { id: number }> {}
✗ Incorrect
Only extends is valid syntax for generic constraints in TypeScript.
Why might you add a constraint like T extends { length: number } to a generic class?
ATo force <code>T</code> to be a string.
BTo prevent <code>T</code> from having a <code>length</code> property.
CTo make <code>T</code> only accept numbers.
DTo ensure <code>T</code> has a <code>length</code> property so you can use it safely inside the class.
✗ Incorrect
The constraint ensures the generic type has a length property, so the class can use it without errors.
What happens if you try to create an instance of a generic class with a type that does not meet the constraint?
ATypeScript will show a compile-time error.
BThe code will run but throw a runtime error.
CThe constraint is ignored and the code compiles.
DThe generic type automatically changes to <code>any</code>.
✗ Incorrect
TypeScript enforces constraints at compile time and will show an error if the type does not satisfy the constraint.
Which of these is NOT a benefit of using generic constraints?
AForcing the generic type to be a specific concrete type
BImproved type safety
CAbility to use specific properties or methods of the generic type
DPreventing invalid types from being used
✗ Incorrect
Constraints limit types but do not force a single concrete type; they allow any type that meets the condition.
Explain what a generic class with constraints is and why it is useful in TypeScript.
Think about how you tell TypeScript what kind of types are allowed for the generic.
You got /5 concepts.
Describe how you would write a generic class that only accepts types with a 'name' string property and how you would use it.
Focus on the constraint and accessing the 'name' property inside the class.
You got /3 concepts.
Practice
(1/5)
1. What is the main purpose of using constraints in a generic class in TypeScript?
easy
A. To ensure the generic type has specific properties or methods
B. To make the class run faster
C. To allow any type without restrictions
D. To convert the generic type to a string
Solution
Step 1: Understand generic constraints
Constraints limit the types that can be used with a generic to those having certain properties or methods.
Step 2: Identify the purpose of constraints
This ensures the generic class can safely use those properties or methods without errors.
Final Answer:
To ensure the generic type has specific properties or methods -> Option A
Quick Check:
Constraints = limit types by properties/methods [OK]
Hint: Constraints limit types to those with needed features [OK]
Common Mistakes:
Thinking constraints improve performance
Believing constraints allow any type
Confusing constraints with type conversion
2. Which of the following is the correct syntax to declare a generic class with a constraint that T must have a 'length' property?
T can be number or string, so value can be either type.
Step 2: Analyze method printValue()
It calls toFixed(2), which exists on number but not on string. TypeScript will produce a compile-time error because toFixed is not available on all possible types for T.
Final Answer:
toFixed is not available on string type -> Option A
Quick Check:
Method uses number-only function on union type [OK]
Hint: Check method compatibility with all constraint types [OK]
Common Mistakes:
Ignoring union type method availability
Thinking constraint syntax is wrong
Assuming missing return type causes error here
5. You want to create a generic class KeyValueStore that only accepts types with a key property of type string and a value property of any type. Which of the following is the correct way to declare this class?
hard
A. class KeyValueStore<T with key: string, value: any> { constructor(public item: T) {} }
B. class KeyValueStore<T> where T has key: string, value: any { constructor(public item: T) {} }
C. class KeyValueStore<T extends { key: string; value: any }> { constructor(public item: T) {} }
D. class KeyValueStore<T: { key: string; value: any }> { constructor(public item: T) {} }