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 in TypeScript?
You declare a generic function by adding a type parameter inside angle brackets <T> before the function's parameters, like: <br>
function example<T>(arg: T): T { return arg; }Click to reveal answer
beginner
What does the <T> mean in a generic function?
The <T> is a placeholder for a type that will be specified when the function is called. It stands for 'Type' and can be replaced with any type like number, string, or a custom type.
Click to reveal answer
intermediate
Can a generic function have multiple type parameters? Give an example.
Yes, a generic function can have multiple type parameters separated by commas, like:<br>
function pair(first: T, second: U): [T, U] { return [first, second]; }Click to reveal answer
intermediate
Why use generic functions instead of using 'any' type?
Generic functions keep type safety by preserving the type information, while 'any' disables type checking and can lead to errors. Generics help catch mistakes during coding.
Click to reveal answer
What does the <T> represent in a TypeScript generic function?
✗ Incorrect
The is a type parameter that acts as a placeholder for any type specified when the function is called.
How do you declare a generic function that returns the same type as its argument?
✗ Incorrect
Option C correctly declares a generic function with type parameter T that returns the same type as the argument.
Can a generic function have more than one type parameter?
✗ Incorrect
Generic functions can have multiple type parameters separated by commas, like .
What is the main advantage of using generic functions over 'any' type?
✗ Incorrect
Generics preserve type information, helping the compiler catch errors, unlike 'any' which disables type checking.
Which of the following is a valid generic function syntax in TypeScript?
✗ Incorrect
Option B correctly declares a generic function with type parameter T and typed argument and return.
Explain how to write a generic function in TypeScript and why it is useful.
Think about how you can make a function work with different types without repeating code.
You got /4 concepts.
Describe the difference between using a generic type parameter and the 'any' type in a function.
Consider how TypeScript helps you avoid mistakes.
You got /4 concepts.