Generic function syntax in Typescript - Time & Space Complexity
We want to see how the time it takes to run a generic function changes as the input size grows.
How does the function's work increase when we give it bigger inputs?
Analyze the time complexity of the following code snippet.
function identity<T>(items: T[]): T[] {
return items.map(item => item);
}
const numbers = [1, 2, 3, 4, 5];
const result = identity(numbers);
This function takes an array of any type and returns a new array with the same items.
- Primary operation: The
mapmethod loops through each item in the array. - How many times: Once for every item in the input array.
As the input array gets bigger, the function does more work by visiting each item once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The work grows directly with the number of items; double the items, double the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the input size.
[X] Wrong: "Generic functions are slower because they handle any type."
[OK] Correct: The generic part only affects types at compile time, not how many steps the function takes at run time.
Understanding how generic functions behave helps you explain your code clearly and shows you know how input size affects performance.
What if we changed the function to use a nested loop inside the map? How would the time complexity change?
Practice
<T> represent in a TypeScript generic function?Solution
Step 1: Understand generic syntax
The<T>syntax is used to declare a generic type parameter in TypeScript functions.Step 2: Identify the role of
It acts as a placeholder for any type that will be provided when the function is called, making the function reusable for different types.TFinal Answer:
A placeholder for a type that will be specified later -> Option AQuick Check:
Generic<T>= Type placeholder [OK]
<T> means 'type to be decided' [OK]- Thinking
Tis a variable name - Confusing
<T>with a function argument - Assuming
<T>is a TypeScript keyword
identity that returns the same type it receives?Solution
Step 1: Check generic declaration
The generic type<T>must be declared before the function parameters.Step 2: Verify parameter and return types
The parameterargshould be of typeT, and the function should return the same typeT.Final Answer:
function identity<T>(arg: T): T { return arg; } -> Option CQuick Check:
Generic function syntax = function identity<T>(arg: T): T { return arg; } [OK]
<T> goes before parameters [OK]- Omitting
<T>before parameters - Not specifying type for
arg - Using
voidas return type incorrectly
function wrapInArray<T>(value: T): T[] { return [value]; }
const result = wrapInArray(5);
console.log(result);Solution
Step 1: Understand function behavior
The functionwrapInArraytakes a value of any typeTand returns an array containing that value.Step 2: Analyze the call with number 5
CallingwrapInArray(5)returns an array with one element:[5].Final Answer:
[5] -> Option DQuick Check:
wrapInArray(5) = [5] [OK]
- Expecting just the value without array
- Confusing output with error
- Misreading return type as void
function getFirstElement<T>(arr: T): T {
return arr[0];
}Solution
Step 1: Check parameter type
The parameterarris declared as typeT, but the function tries to accessarr[0], which requiresarrto be an array.Step 2: Correct parameter type
To access the first element,arrshould be of typeT[](array ofT), not justT.Final Answer:
Parameterarrshould be an array typeT[], notT-> Option AQuick Check:
Array parameter needsT[]type [OK]
T[] type, not just T [OK]- Using
Tinstead ofT[]for arrays - Returning wrong type
- Forgetting to declare generic
<T>
mergeObjects that takes two objects of possibly different types and returns a new object combining both. Which is the correct syntax to declare this function?Solution
Step 1: Understand the requirement
The function should accept two objects of different types and return a combined object containing properties of both.Step 2: Check generic parameters and return type
Using two generic typesTandUallows different input types. The return typeT & Umeans an object with properties from both types.Step 3: Verify function body
The spread operator{...obj1, ...obj2}correctly merges the two objects.Final Answer:
function mergeObjects<T, U>(obj1: T, obj2: U): T & U { return {...obj1, ...obj2}; } -> Option BQuick Check:
Two generics + intersection return = function mergeObjects(obj1: T, obj2: U): T & U { return {...obj1, ...obj2}; } [OK]
T & U [OK]- Using same generic type for both parameters
- Returning just
objectloses type info - Not using intersection type for return
Ready to prove it?
Pass the test and this pattern moves unknown
