Bird
Raised Fist0
Typescriptprogramming~5 mins

Generic functions with arrays in Typescript - Cheat Sheet & Quick Revision

Choose your learning style10 modes available
Recall & Review
beginner
What is a generic function in TypeScript?
A generic function is a function that can work with any data type, allowing you to write flexible and reusable code by using type variables.
Click to reveal answer
beginner
How do you declare a generic function that accepts an array of any type and returns the first element?
You declare it using a type parameter like <T> and use it for the array and return type:
function firstElement<T>(arr: T[]): T | undefined {
return arr[0];
}
Click to reveal answer
intermediate
Why use generic functions with arrays instead of using 'any' type?
Generics keep type safety by preserving the type information, so you get better error checking and autocompletion, unlike 'any' which disables type checks.
Click to reveal answer
beginner
What does this function do?
function reverseArray<T>(arr: T[]): T[] {
return arr.slice().reverse();
}
It takes an array of any type T, creates a copy of it, reverses the order of elements, and returns the reversed array without changing the original.
Click to reveal answer
beginner
How can you call a generic function with an array of numbers to get the first element?
You can call it like this:<br><pre>const nums = [10, 20, 30];<br>const first = firstElement<number>(nums);<br>console.log(first); // Output: 10</pre>
Click to reveal answer
What does the <T> mean in a TypeScript function declaration?
AIt specifies the function is asynchronous.
BIt is a syntax error.
CIt means the function returns a string.
DIt declares a generic type parameter.
What is the return type of this function?
function getLast<T>(arr: T[]): T | undefined {
return arr[arr.length - 1];
}
AT or undefined
BT[]
Cvoid
DT
Why is it better to use generics instead of 'any' for array functions?
AGenerics remove all type checks.
BGenerics make the code slower.
CGenerics keep type safety and help catch errors.
DGenerics only work with numbers.
Which of these is a correct way to define a generic function that returns the length of an array?
Afunction length(arr: any): number { return arr.length; }
Bfunction length<T>(arr: T[]): number { return arr.length; }
Cfunction length(arr: T): number { return arr.length; }
Dfunction length<T>(arr: T): T { return arr.length; }
What will this code output?
function identity<T>(arr: T[]): T[] { return arr; }
console.log(identity(['a', 'b', 'c']));
A['a', 'b', 'c']
Bundefined
CError
D['c', 'b', 'a']
Explain how to write a generic function in TypeScript that takes an array and returns its first element.
Think about how to keep the function flexible for any array type.
You got /4 concepts.
    Describe the benefits of using generic functions with arrays instead of using the 'any' type.
    Consider what happens when you lose type information.
    You got /4 concepts.

      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