Generic class with constraints in Typescript - Time & Space Complexity
We want to see how the time needed changes when using a generic class with constraints in TypeScript.
How does the program's work grow as the input size grows?
Analyze the time complexity of the following code snippet.
class Container<T extends { id: number }> {
items: T[] = [];
add(item: T) {
this.items.push(item);
}
findById(id: number): T | undefined {
return this.items.find(item => item.id === id);
}
}
This class stores items with an id and can add items or find one by its id.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
findmethod loops through theitemsarray to check each item'sid. - How many times: It checks each item once until it finds a match or reaches the end.
As the number of items grows, the time to find an item grows roughly the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to find an item grows linearly as the list gets longer.
[X] Wrong: "Using a generic class with constraints makes the search faster automatically."
[OK] Correct: The generic constraint only ensures the item has an id, but the search still checks items one by one.
Understanding how generic classes work with constraints and their time costs helps you explain your code clearly and shows you think about efficiency.
"What if we changed the items array to a Map keyed by id? How would the time complexity change?"
Practice
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 AQuick Check:
Constraints = limit types by properties/methods [OK]
- Thinking constraints improve performance
- Believing constraints allow any type
- Confusing constraints with type conversion
Solution
Step 1: Recall TypeScript generic constraint syntax
TypeScript usesextendskeyword to constrain generics.Step 2: Match syntax for property constraint
To require a property, use an object type with that property, e.g.,{ length: number }.Final Answer:
class Box<T extends { length: number }> {} -> Option DQuick Check:
Generic constraints use extends with type shape [OK]
- Using 'where' or 'with' keywords (not valid in TypeScript)
- Using colon ':' instead of 'extends'
- Omitting the property type in constraint
class Container<T extends { name: string }> {
item: T;
constructor(item: T) {
this.item = item;
}
getName() {
return this.item.name;
}
}
const obj = { name: 'Box', size: 10 };
const c = new Container(obj);
console.log(c.getName());Solution
Step 1: Analyze the generic constraint and object
The class requires T to have a 'name' string property. The object has 'name' and 'size', so it fits.Step 2: Understand method getName()
It returns this.item.name, which is 'Box' from the object.Final Answer:
'Box' -> Option BQuick Check:
Accessing constrained property returns 'Box' [OK]
- Assuming extra properties cause errors
- Thinking output is undefined if extra props exist
- Confusing runtime errors with compile-time checks
class DataHolder<T extends number | string> {
value: T;
constructor(value: T) {
this.value = value;
}
printValue() {
console.log(this.value.toFixed(2));
}
}Solution
Step 1: Check the generic constraint
T can be number or string, so value can be either type.Step 2: Analyze method printValue()
It callstoFixed(2), which exists on number but not on string. TypeScript will produce a compile-time error becausetoFixedis not available on all possible types for T.Final Answer:
toFixed is not available on string type -> Option AQuick Check:
Method uses number-only function on union type [OK]
- Ignoring union type method availability
- Thinking constraint syntax is wrong
- Assuming missing return type causes error here
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?Solution
Step 1: Recall TypeScript generic constraint syntax
Useextendswith an object type to constrain T to have specific properties.Step 2: Match the required properties
The constraint must requirekey: stringandvalue: anyproperties.Step 3: Verify constructor syntax
The constructor correctly accepts an item of type T and assigns it.Final Answer:
class KeyValueStore<T extends { key: string; value: any }> { constructor(public item: T) {} } -> Option CQuick Check:
Use extends with object type for property constraints [OK]
- Using 'where' or 'with' keywords (not valid in TypeScript)
- Using colon ':' instead of 'extends'
- Omitting property types in constraint
Ready to prove it?
Pass the test and this pattern moves unknown
