What if one simple function could work perfectly with any kind of data you throw at it?
Why Generic arrow functions in Typescript? - Purpose & Use Cases
Imagine you need to write many small functions that do similar things but work with different types of data, like numbers, strings, or objects. Writing each function separately means a lot of repeated code.
Writing separate functions for each data type is slow and boring. It's easy to make mistakes when copying and changing code. Also, if you want to change the logic, you must update many places, which wastes time and causes bugs.
Generic arrow functions let you write one flexible function that works with any data type. You write the logic once, and TypeScript helps you keep it safe and correct for all types. This saves time and reduces errors.
function identityNumber(x: number): number { return x; }
function identityString(x: string): string { return x; }const identity = <T>(x: T): T => x;
It enables writing reusable, type-safe functions that adapt to any data type effortlessly.
Think of a function that returns the first item of any list, whether it's a list of names, ages, or products. Generic arrow functions let you write this once and use it everywhere.
Writing separate functions for each type is repetitive and error-prone.
Generic arrow functions let you write one flexible function for all types.
This saves time, reduces bugs, and keeps your code clean and safe.
Practice
What does the <T> represent in a generic arrow function in TypeScript?
Solution
Step 1: Understand generic type parameters
The<T>syntax declares a generic type parameter, which acts as a placeholder for any type.Step 2: Recognize its purpose in functions
This allows the function to work with different types while keeping type safety.Final Answer:
A placeholder for a type that will be specified later -> Option BQuick Check:
Generic type parameter = placeholder type [OK]
- Confusing <T> with a variable name
- Thinking <T> is a keyword like const or let
- Assuming <T> is an operator
Which of the following is the correct syntax for a generic arrow function that returns the same type it receives?
?Solution
Step 1: Check generic arrow function syntax
The generic type parameter<T>must come immediately after the function name without an equals sign.Step 2: Verify arrow function structure
The function takes an argument of typeTand returns the same typeT.const identity = <T>(arg: T): T => arg;matches this syntax correctly.Final Answer:
const identity = <T>(arg: T): T => arg; -> Option CQuick Check:
Correct generic arrow function syntax =const identity = <T>(arg: T): T => arg;[OK]
- Adding an equals sign after <T>
- Misplacing parentheses around <T>
- Using incorrect arrow function syntax
What will be the output of this TypeScript code?
const wrapInArray = <T>(value: T): T[] => [value];
console.log(wrapInArray(5));
console.log(wrapInArray('hello'));Solution
Step 1: Understand the generic function behavior
The functionwrapInArraytakes a value of any typeTand returns an array containing that value.Step 2: Analyze the console.log outputs
CallingwrapInArray(5)returns[5], andwrapInArray('hello')returns['hello'].Final Answer:
[5] ['hello'] -> Option AQuick Check:
Generic function returns array with input value [OK]
- Expecting output without array brackets
- Thinking it returns a tuple
- Confusing types causing errors
Identify the error in this generic arrow function and choose the corrected version:
const getFirst = <T> = (arr: T[]): T => {
return 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 DQuick Check:
Generic arrow function syntax =const getFirst = <T>(arr: T[]): T => arr[0];[OK]
- Adding equals sign after <T>
- Omitting generic parameter <T>
- Incorrect arrow function syntax
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}));Solution
Step 1: Understand the generic parameters and return type
The function takes two objects of typesTandUand returns their intersection typeT & 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.Step 3: Predict the output of the console.log
CallingmergeObjects({a: 1}, {b: 2})returns{ a: 1, b: 2 }.Final Answer:
{ a: 1, b: 2 } -> Option AQuick Check:
Spread merge of two objects = combined object [OK]
- Expecting only first or second object properties
- Confusing intersection type with union
- Thinking it causes runtime error
Ready to prove it?
Pass the test and this pattern moves unknown
