A generic arrow function is a function written with arrow syntax that uses type parameters to work with different data types while keeping type safety.
Click to reveal answer
beginner
How do you declare a generic arrow function with one type parameter <T>?
You write the function with <T> before the parameters, like: <br><code>const func = <T>(arg: T): T => arg;</code>
Click to reveal answer
intermediate
Why use generic arrow functions instead of regular functions?
Generic arrow functions provide concise syntax and allow type flexibility with less code, making them easy to read and maintain.
Click to reveal answer
beginner
What does this generic arrow function do?<br><code>const identity = <T>(value: T): T => value;</code>
It returns the same value it receives, keeping the type of the input and output the same.
Click to reveal answer
intermediate
Can generic arrow functions have multiple type parameters? Give an example.
A. const getFirst = <T> (arr: T[]): T => { return arr[0]; };
B. const getFirst = (arr: T[]): T => arr[0];
C. const getFirst = <T>: (arr: T[]) => T => arr[0];
D. const getFirst = <T>(arr: T[]): T => arr[0];
Solution
Step 1: Identify incorrect syntax in original code
The original code incorrectly uses an equals sign after <T>, which is not valid syntax for generic arrow functions.
Step 2: Choose the correct syntax
const getFirst = <T>(arr: T[]): T => arr[0]; correctly places <T> immediately after the function name without an equals sign and uses concise arrow function syntax.
Final Answer:
const getFirst = <T>(arr: T[]): T => arr[0]; -> Option D
Quick Check:
Generic arrow function syntax = const getFirst = <T>(arr: T[]): T => arr[0]; [OK]
Hint: No equals sign after <T> in generic arrow functions [OK]
Common Mistakes:
Adding equals sign after <T>
Omitting generic parameter <T>
Incorrect arrow function syntax
5.
Given this generic arrow function, what is the output of mergeObjects({a: 1}, {b: 2})?
const mergeObjects = <T, U>(obj1: T, obj2: U): T & U => ({ ...obj1, ...obj2 });
console.log(mergeObjects({a: 1}, {b: 2}));
hard
A. { a: 1, b: 2 }
B. { a: 1 }
C. { b: 2 }
D. TypeError at runtime
Solution
Step 1: Understand the generic parameters and return type
The function takes two objects of types T and U and returns their intersection type T & U, meaning it combines properties from both.
Step 2: Analyze the spread operator usage
The spread operator merges properties from both objects into a new object containing all keys and values.