Bird
Raised Fist0
Typescriptprogramming~10 mins

Generic functions with arrays in Typescript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Generic functions with arrays
Start: Call generic function with array
↓
Function receives array of type T[
↓
Process each element (e.g., map, filter)
↓
Return new array of type T[
↓
End
The generic function takes an array of any type T, processes it, and returns a new array of the same type.
Execution Sample
Typescript
function identityArray<T>(arr: T[]): T[] {
  return arr.map(item => item);
}

const nums = [1, 2, 3];
const result = identityArray(nums);
This function returns a new array identical to the input array, preserving the type.
Execution Table
StepActionInput ArrayProcessingOutput Array
1Call identityArray with nums[1, 2, 3]Start processing each element—
2Process element 1[1, 2, 3]Map item=1 → 1[1]
3Process element 2[1, 2, 3]Map item=2 → 2[1, 2]
4Process element 3[1, 2, 3]Map item=3 → 3[1, 2, 3]
5Return new array[1, 2, 3]All elements processed[1, 2, 3]
6Assign to result——[1, 2, 3]
💡 All elements processed and returned as a new array of the same type.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
arrundefined[1, 2, 3][1, 2, 3][1, 2, 3][1, 2, 3]
itemundefined1233
output array[][1][1, 2][1, 2, 3][1, 2, 3]
resultundefinedundefinedundefinedundefined[1, 2, 3]
Key Moments - 3 Insights
Why does the function use <T> and how does it keep the array type?
The <T> tells TypeScript to use a generic type. The input array is T[], so the output is also T[], keeping the same type as the input (see execution_table steps 1 and 5).
Does the function change the original array?
No, it uses map to create a new array with the same elements (see execution_table rows 2-5), so the original array stays unchanged.
What if we pass an array of strings instead of numbers?
The function works the same way because it is generic. The type T becomes string, and the output array is string[] (not shown here but same logic applies).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output array after processing the second element?
A[1, 2, 3]
B[1]
C[1, 2]
D[]
💡 Hint
Check the 'Output Array' column at Step 3 in the execution_table.
At which step does the function return the new array?
AStep 5
BStep 4
CStep 6
DStep 2
💡 Hint
Look for the step where the action is 'Return new array' in the execution_table.
If we change the function to return arr without map, how would the output array change?
AOutput array would contain doubled elements
BOutput array would be the same as input array reference
COutput array would be empty
DOutput array would be undefined
💡 Hint
Think about what happens if map is removed and the original array is returned directly.
Concept Snapshot
Generic functions use <T> to work with any type.
Input and output arrays keep the same type T[].
Use array methods like map to process elements.
The function returns a new array, not modifying the original.
This keeps code reusable and type-safe.
Full Transcript
This visual trace shows how a generic function in TypeScript works with arrays. The function identityArray takes an array of any type T and returns a new array of the same type. Step by step, each element is processed using map, creating a new array identical to the input. Variables like arr, item, and output array change as the function runs. Key points include understanding the generic type <T> keeps the array type consistent, the original array is not changed, and the function can work with any type of array. The quiz questions help check understanding of the output array at different steps and the effect of changing the function to return the original array directly.

Practice

(1/5)
1.

What is the main purpose of using a generic function with <T> in TypeScript when working with arrays?

easy
A. To allow the function to work with arrays of any type without rewriting code.
B. To restrict the function to only work with number arrays.
C. To convert all array elements to strings.
D. To make the function run faster by using a specific type.

Solution

  1. Step 1: Understand generic type <T>

    The generic type <T> allows a function to accept any type, making it reusable for different data types.
  2. Step 2: Apply to arrays

    Using <T> with arrays means the function can handle arrays of numbers, strings, or any other type without rewriting the function.
  3. Final Answer:

    To allow the function to work with arrays of any type without rewriting code. -> Option A
  4. Quick Check:

    Generic <T> = reusable for any type [OK]
Hint: Generic <T> means any type works [OK]
Common Mistakes:
  • Thinking generic restricts to one type
  • Assuming generic converts types
  • Believing generic improves speed only
2.

Which of the following is the correct syntax to declare a generic function firstElement that returns the first element of an array of any type?

function firstElement(____): T | undefined {
  return arr[0];
}
easy
A. arr: T[]
B. <T> arr: T[]
C. <T>(arr: T[])
D. (arr: any[])

Solution

  1. Step 1: Identify generic function syntax

    Generic functions declare the type parameter before the argument list, like function fnName<T>(args).
  2. Step 2: Match syntax to example

    The correct syntax is function firstElement<T>(arr: T[]): T | undefined to accept an array of type T.
  3. Final Answer:

    <T>(arr: T[]) -> Option C
  4. Quick Check:

    Generic syntax = <T>(args) [OK]
Hint: Generic type goes before parameters in function [OK]
Common Mistakes:
  • Placing <T> after parameters
  • Omitting <T> entirely
  • Using incorrect parameter types
3.

What will be the output of the following TypeScript code?

function getLastElement<T>(arr: T[]): T | undefined {
  return arr.length ? arr[arr.length - 1] : undefined;
}

const nums = [10, 20, 30];
const result = getLastElement(nums);
console.log(result);
medium
A. 30
B. 10
C. undefined
D. Error

Solution

  1. Step 1: Understand function behavior

    The function returns the last element if the array is not empty; otherwise, it returns undefined.
  2. Step 2: Apply to given array

    The array nums is [10, 20, 30], so the last element is 30, which is returned and logged.
  3. Final Answer:

    30 -> Option A
  4. Quick Check:

    Last element of [10,20,30] = 30 [OK]
Hint: Last element is at index length-1 [OK]
Common Mistakes:
  • Returning first element instead
  • Ignoring empty array case
  • Expecting error due to generics
4.

Identify the error in this generic function and select the corrected version:

function wrapInArray<T>(item: T): T[] {
  return item;
}
medium
A. Remove generic <T> since it's not needed.
B. Change return to [item] to return an array containing the item.
C. Change parameter type to T[] to match return type.
D. Change return type to T instead of T[].

Solution

  1. Step 1: Analyze function return type

    The function promises to return an array of type T[], but returns item which is type T, not an array.
  2. Step 2: Fix return statement

    Wrapping item in square brackets [item] creates an array containing the item, matching the return type.
  3. Final Answer:

    Change return to [item] to return an array containing the item. -> Option B
  4. Quick Check:

    Return array by wrapping item in [] [OK]
Hint: Return arrays with brackets [] around item [OK]
Common Mistakes:
  • Returning item directly instead of array
  • Changing parameter type unnecessarily
  • Removing generics without reason
5.

You want to create a generic function filterNonEmpty that takes an array of any type T and returns a new array excluding null and undefined values. Which implementation correctly uses generics and array filtering?

hard
A. function filterNonEmpty<T>(arr: T[]): T[] { return arr.filter(item => item != null); }
B. function filterNonEmpty(arr: T[]): T[] { return arr.filter(item => item !== null && item !== undefined); }
C. function filterNonEmpty<T>(arr: T[]): (T | null | undefined)[] { return arr.filter(item => item != null); }
D. function filterNonEmpty<T>(arr: (T | null | undefined)[]): T[] { return arr.filter(item => item != null); }

Solution

  1. Step 1: Define input and output types

    The input array can contain T, null, or undefined, so its type is (T | null | undefined)[]. The output should be only T[].
  2. Step 2: Filter out null and undefined

    Using filter(item => item != null) removes both null and undefined values safely.
  3. Final Answer:

    function filterNonEmpty<T>(arr: (T | null | undefined)[]): T[] { return arr.filter(item => item != null); } -> Option D
  4. Quick Check:

    Filter null/undefined from mixed array [OK]
Hint: Input type includes null/undefined, output excludes them [OK]
Common Mistakes:
  • Not typing input to include null/undefined
  • Returning wrong output type
  • Using strict !== null only, missing undefined
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard