Generic interface declaration in Typescript - Time & Space Complexity
We want to understand how the time it takes to use a generic interface changes as the input size grows.
Specifically, how does the code inside the interface behave when handling different amounts of data?
Analyze the time complexity of the following code snippet.
interface Box<T> {
contents: T[];
add(item: T): void;
get(index: number): T | undefined;
}
class SimpleBox<T> implements Box<T> {
contents: T[] = [];
add(item: T) { this.contents.push(item); }
get(index: number) { return this.contents[index]; }
}
This code defines a generic interface and a class that stores items in an array, allowing adding and getting items by index.
- Primary operation: Adding an item uses array push (amortized constant time), getting an item accesses array by index (constant time).
- How many times: Each add or get operation happens once per call, no loops inside these methods.
Each add or get operation takes about the same time no matter how many items are stored.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 operations for 10 adds or gets |
| 100 | 100 operations for 100 adds or gets |
| 1000 | 1000 operations for 1000 adds or gets |
Pattern observation: The time grows directly with the number of calls, but each call is quick and does not depend on the total size.
Time Complexity: O(1)
This means each add or get operation takes the same small amount of time no matter how many items are stored.
[X] Wrong: "Adding or getting items takes longer as the box fills up because the array grows."
[OK] Correct: The array push and index access are designed to be very fast and do not slow down with more items.
Understanding how generic interfaces work with data storage helps you explain how your code handles different data sizes efficiently.
"What if the get method searched for an item by value instead of index? How would the time complexity change?"
Practice
<T> represent in a TypeScript generic interface declaration?Solution
Step 1: Understand generic syntax
The<T>syntax in TypeScript is used to declare a generic type parameter, which acts as a placeholder for a type.Step 2: Identify the role of
This placeholder allows the interface to be flexible and reusable with different types specified later.TFinal Answer:
A placeholder for a type that will be specified later -> Option DQuick Check:
Generic<T>= Type placeholder [OK]
<T> means 'type to be given later' [OK]- Thinking
Tis a variable or constant - Confusing
<T>with a function parameter - Assuming
Tis always a string type
Box with a type parameter T?Solution
Step 1: Check interface declaration syntax
In TypeScript, interfaces are declared with the keywordinterfacefollowed by the name and optional generic parameters in angle brackets.Step 2: Verify correct use of braces and type parameter
The correct syntax includes curly braces to define the interface body and uses<T>to declare the generic type parameter.Final Answer:
interface Box<T> { content: T; } -> Option BQuick Check:
Generic interface syntax = interface Box<T> { content: T; } [OK]
<T> and braces {} [OK]- Omitting the generic parameter
<T> - Missing curly braces around interface body
- Using equals sign instead of braces
interface Container<T> { value: T; }What is the output of this code?
const numberContainer: Container<number> = { value: 42 };
console.log(numberContainer.value);Solution
Step 1: Understand the generic interface usage
The interfaceContainer<T>expects a type parameter. Here,numberis specified, sovaluemust be a number.Step 2: Analyze the assigned object and console output
The object{ value: 42 }matches the interface withvalueas a number. LoggingnumberContainer.valueprints42.Final Answer:
42 -> Option CQuick Check:
Generic with number type outputs 42 [OK]
- Expecting a runtime error due to generics
- Confusing generic type with runtime type enforcement
- Assuming output is undefined or null
interface Pair<T> {
first: T;
second: T;
}
const pair: Pair = { first: 'hello', second: 'world' };Solution
Step 1: Check interface usage with generics
The interfacePair<T>requires a type argument when used. Here,Pairis used without specifying<T>.Step 2: Identify the missing generic argument error
TypeScript will report an error because the generic type parameter is missing when declaringpair.Final Answer:
Missing generic type argument when using Pair -> Option AQuick Check:
Generic interface usage needs type argument [OK]
- Forgetting to add
<Type>when using generic interfaces - Assuming default type if omitted
- Confusing property types with generic parameter
Result<T> that holds a data property of type T and a success boolean. Which of the following implementations correctly uses this interface to type a variable holding a string result?Solution
Step 1: Understand the generic interface requirements
The interfaceResult<T>expects adataproperty of typeTand asuccessboolean.Step 2: Check each option for correct type usage
const res: Result<string> = { data: 123, success: true }; assigns a number todatabut expects a string type, so it's incorrect.
const res: Result<string> = { data: 'Done', success: true }; correctly assigns a string todataand includessuccess.
const res: Result = { data: 'Done', success: true }; omits the generic type argument, which is required.
const res: Result<number> = { data: 'Done', success: true }; usesnumbertype but assigns a string, causing a type mismatch.Final Answer:
const res: Result<string> = { data: 'Done', success: true }; -> Option AQuick Check:
Generic type matches property type = const res: Result<string> = { data: 'Done', success: true }; [OK]
- Assigning wrong type to generic property
- Omitting generic type argument
- Mixing up generic type parameters
Ready to prove it?
Pass the test and this pattern moves unknown
