What if one simple function could handle all your data types perfectly?
Why Generic function syntax in Typescript? - Purpose & Use Cases
Imagine you want to write a function that works with different types of data, like numbers, strings, or even objects. Without generic functions, you'd have to write a new function for each type, which quickly becomes messy and repetitive.
Writing separate functions for each data type is slow and error-prone. It leads to duplicated code that is hard to maintain. If you want to change the logic, you must update every version, increasing the chance of mistakes.
Generic function syntax lets you write one flexible function that works with any data type. It uses placeholders for types, so the function adapts automatically. This keeps your code clean, reusable, and easy to maintain.
function identityNumber(value: number): number { return value; }
function identityString(value: string): string { return value; }function identity<T>(value: T): T { return value; }It enables you to create reusable, type-safe functions that work with any data type without rewriting code.
Think of a function that returns the first item from any list, whether it's a list of names, numbers, or objects. With generics, one function handles all cases safely.
Writing separate functions for each type is inefficient and error-prone.
Generic functions use type placeholders to work with any data type.
This leads to cleaner, reusable, and safer code.
Practice
<T> represent in a TypeScript generic function?Solution
Step 1: Understand generic syntax
The<T>syntax is used to declare a generic type parameter in TypeScript functions.Step 2: Identify the role of
It acts as a placeholder for any type that will be provided when the function is called, making the function reusable for different types.TFinal Answer:
A placeholder for a type that will be specified later -> Option AQuick Check:
Generic<T>= Type placeholder [OK]
<T> means 'type to be decided' [OK]- Thinking
Tis a variable name - Confusing
<T>with a function argument - Assuming
<T>is a TypeScript keyword
identity that returns the same type it receives?Solution
Step 1: Check generic declaration
The generic type<T>must be declared before the function parameters.Step 2: Verify parameter and return types
The parameterargshould be of typeT, and the function should return the same typeT.Final Answer:
function identity<T>(arg: T): T { return arg; } -> Option CQuick Check:
Generic function syntax = function identity<T>(arg: T): T { return arg; } [OK]
<T> goes before parameters [OK]- Omitting
<T>before parameters - Not specifying type for
arg - Using
voidas return type incorrectly
function wrapInArray<T>(value: T): T[] { return [value]; }
const result = wrapInArray(5);
console.log(result);Solution
Step 1: Understand function behavior
The functionwrapInArraytakes a value of any typeTand returns an array containing that value.Step 2: Analyze the call with number 5
CallingwrapInArray(5)returns an array with one element:[5].Final Answer:
[5] -> Option DQuick Check:
wrapInArray(5) = [5] [OK]
- Expecting just the value without array
- Confusing output with error
- Misreading return type as void
function getFirstElement<T>(arr: T): T {
return arr[0];
}Solution
Step 1: Check parameter type
The parameterarris declared as typeT, but the function tries to accessarr[0], which requiresarrto be an array.Step 2: Correct parameter type
To access the first element,arrshould be of typeT[](array ofT), not justT.Final Answer:
Parameterarrshould be an array typeT[], notT-> Option AQuick Check:
Array parameter needsT[]type [OK]
T[] type, not just T [OK]- Using
Tinstead ofT[]for arrays - Returning wrong type
- Forgetting to declare generic
<T>
mergeObjects that takes two objects of possibly different types and returns a new object combining both. Which is the correct syntax to declare this function?Solution
Step 1: Understand the requirement
The function should accept two objects of different types and return a combined object containing properties of both.Step 2: Check generic parameters and return type
Using two generic typesTandUallows different input types. The return typeT & Umeans an object with properties from both types.Step 3: Verify function body
The spread operator{...obj1, ...obj2}correctly merges the two objects.Final Answer:
function mergeObjects<T, U>(obj1: T, obj2: U): T & U { return {...obj1, ...obj2}; } -> Option BQuick Check:
Two generics + intersection return = function mergeObjects(obj1: T, obj2: U): T & U { return {...obj1, ...obj2}; } [OK]
T & U [OK]- Using same generic type for both parameters
- Returning just
objectloses type info - Not using intersection type for return
Ready to prove it?
Pass the test and this pattern moves unknown
