0
0
Typescriptprogramming~5 mins

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

Choose your learning style9 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: <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?
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?<br>
function getLast<T>(arr: T[]): T | undefined {<br>  return arr[arr.length - 1];<br>}
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?<br>
function identity<T>(arr: T[]): T[] { return arr; }<br>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.