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: <br>
function firstElement<T>(arr: T[]): T | undefined {<br> return arr[0];<br>}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?<br>
function reverseArray<T>(arr: T[]): T[] {<br> return arr.slice().reverse();<br>}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?
✗ Incorrect
The declares a generic type parameter that can be used inside the function for flexible typing.
What is the return type of this function?<br>
function getLast<T>(arr: T[]): T | undefined {<br> return arr[arr.length - 1];<br>}✗ Incorrect
The function returns the last element of the array or undefined if the array is empty.
Why is it better to use generics instead of 'any' for array functions?
✗ Incorrect
Generics preserve type information, so TypeScript can check types and prevent mistakes.
Which of these is a correct way to define a generic function that returns the length of an array?
✗ Incorrect
Option B correctly uses a generic type parameter T for an array and returns a number.
What will this code output?<br>
function identity<T>(arr: T[]): T[] { return arr; }<br>console.log(identity(['a', 'b', 'c']));✗ Incorrect
The function returns the same array it receives, so the output is ['a', 'b', 'c'].
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.