Skip to content
-
Interesting Facts About Generics in TypeScript
Last Updated :
20 Mar, 2025
TypeScript generics provide a powerful way to create reusable, type-safe components and functions that work with multiple types. They improve flexibility, reduce redundancy, and ensure strict type constraints without sacrificing reusability.
1. Generics Make Functions Flexible
Generics allow you to create functions that work with any type while keeping your code type safe.
JavaScript
function identity<T>(value: T): T {
return value;
}
const result = identity("Hello"); // result is of type string
2. Tuples Keep Their Order with Generics
Generics ensure that tuples maintain their exact structure and order, unlike regular arrays.
JavaScript
type Swap<T extends [any, any]> = [T[1], T[0]];
type Swapped = Swap<[string, number]>;
3. Generics Can Have Multiple Rules
Generics can enforce multiple constraints, making them even more powerful and flexible.
JavaScript
function merge<T extends object, U extends object>(obj1: T, obj2: U): T & U {
return { ...obj1, ...obj2 };
}
const merged = merge({ name: "Alice" }, { age: 25 }); // { name: "Alice", age: 25 }
4. Transform Objects Dynamically with Generics
Generics can dynamically change object structures using mapped types.
JavaScript
type ReadOnly<T> = { readonly [K in keyof T]: T[K] };
type User = { name: string; age: number };
type ReadOnlyUser = ReadOnly<User>;
5. Generics Can Make Decisions with Conditional Types
Generics can use conditional logic to decide types based on conditions.
JavaScript
type IsString<T> = T extends string ? "Yes" : "No";
type Result1 = IsString<string>; // "Yes"
type Result2 = IsString<number>; // "No"
6. Create Reusable Classes with Generics
Generics make classes adaptable to different data types, reducing code duplication.
JavaScript
class Box<T> {
constructor(private item: T) {}
getItem(): T { return this.item; }
}
const stringBox = new Box("Hello"); // Box<string>
const numberBox = new Box(42); // Box<number>
7. TypeScript Guesses Types for You
TypeScript can automatically figure out generic types based on how you use them.
JavaScript
function wrap<T>(value: T) {
return [value];
}
const numbers = wrap(10); // number[]
const words = wrap("hello"); // string[]
8. Generics Can Be Recursive
Generics can handle nested structures, making them perfect for complex data.
JavaScript
type NestedArray<T> = T | NestedArray<T>[];
const numbers: NestedArray<number> = [1, [2, [3, [4]]]; // Nested array of numbers
9. Simplify Function Overloads with Generics
Generics can replace multiple function overloads with a single, dynamic solution.
JavaScript
function identity<T>(value: T): T {
return value;
}
const result1 = identity("Hello"); // string
const result2 = identity(42); // number
10. Generics Can Work with Length
Generics can enforce rules based on properties like length, making them versatile.
JavaScript
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length > b.length ? a : b;
}
const longerString = longest("apple", "banana"); // "banana"
const longerArray = longest([1, 2], [3, 4, 5]); // [3, 4, 5]
Similar Reads
How to Create Arrays of Generic Interfaces in TypeScript ? In TypeScript, managing data structures effectively is crucial for building robust applications. Arrays of generic interfaces provide a powerful mechanism to handle varied data types while maintaining type safety and flexibility. There are various methods for constructing arrays of generic interface
3 min read
How to Make a Generic Sorting Function in TypeScript ? Sorting is a fundamental operation in programming, allowing us to organize data in a specific order for easier manipulation and retrieval. In TypeScript, creating a generic sorting function provides flexibility and reusability across different data types. Table of Content Using Array.prototype.sort(
4 min read
Function Overloading With Generics In TypeScript TypeScript has the ability to overload functions which means multiple signatures may be defined for one single function, this comes in handy when you want a function to behave in a certain way based on the provided parameters. In this article, we will be looking at how function overloading is done u
4 min read
Interesting Facts About Object Types and Interfaces in TypeScript TypeScript enhances object types and interfaces with strong typing, extendibility, and dynamic features, making code more structured and maintainable. Mastering these concepts improves scalability, flexibility, and type safety in applications.1. Interfaces Can Describe FunctionsInterfaces in TypeScr
3 min read
TypeScript Using Class Types in Generics TypeScript Using class types in generics allows you to create more flexible and reusable code by specifying that a generic parameter should be a class constructor. This is particularly useful when you want to work with instances of classes but want to keep the code type safe. You can define a generi
3 min read
TypeScript Interview Questions and Answers TypeScript, a robust, statically typed superset of JavaScript, has become a go-to language for building scalable and maintainable applications. Developed by Microsoft, it enhances JavaScript by adding static typing and modern ECMAScript features, enabling developers to catch errors early and improve
15+ min read
`;
$(commentSectionTemplate).insertBefore(".article--recommended");
}
loadComments();
});
});
function loadComments() {
if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) {
if (!isfollowingApiCall) {
isfollowingApiCall = true;
setTimeout(function(){
if (loginData && loginData.isLoggedIn) {
if (loginData.userName !== $('#followAuthor').val()) {
is_following();
} else {
$('.profileCard-profile-picture').css('background-color', '#E7E7E7');
}
} else {
$('.follow-btn').removeClass('hideIt');
}
}, 3000);
}
}
});
}
$(".accordion-header").click(function() {
var arrowIcon = $(this).find('.bottom-arrow-icon');
arrowIcon.toggleClass('rotate180');
});
});
window.isReportArticle = false;
function report_article(){
if (!loginData || !loginData.isLoggedIn) {
const loginModalButton = $('.login-modal-btn')
if (loginModalButton.length) {
loginModalButton.click();
}
return;
}
if(!window.isReportArticle){
//to add loader
$('.report-loader').addClass('spinner');
jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', {
PRACTICE_API_URL: practiceAPIURL,
PRACTICE_URL:practiceURL
},function(responseTxt, statusTxt, xhr){
if(statusTxt == "error"){
alert("Error: " + xhr.status + ": " + xhr.statusText);
}
});
}else{
window.scrollTo({ top: 0, behavior: 'smooth' });
$("#report_modal_content").show();
}
}
function closeShareModal() {
const shareOption = document.querySelector('[data-gfg-action="share-article"]');
shareOption.classList.remove("hover_share_menu");
let shareModal = document.querySelector(".hover__share-modal-container");
shareModal && shareModal.remove();
}
function openShareModal() {
closeShareModal(); // Remove existing modal if any
let shareModal = document.querySelector(".three_dot_dropdown_share");
shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" }));
document.querySelector(".hover__share-modal-container").append(
Object.assign(document.createElement('div'), { className: "share__modal" }),
);
document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" }));
const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"];
socialOptions.forEach((socialOption) => {
const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" });
const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` });
const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` });
const shareLink = (socialOption === "Copy Link") ?
Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) :
Object.assign(document.createElement('a'), { className: "link-container" });
if (socialOption === "LinkedIn") {
shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`);
shareLink.setAttribute('target', '_blank');
}
if (socialOption === "WhatsApp") {
shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`);
shareLink.setAttribute('target', "_blank");
}
if (socialOption === "Twitter") {
shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`);
shareLink.setAttribute('target', "_blank");
}
shareLink.append(icon, socialText);
socialContainer.append(shareLink);
document.querySelector(".share__modal").appendChild(socialContainer);
//adding copy url functionality
if(socialOption === "Copy Link") {
shareLink.addEventListener("click", function() {
var tempInput = document.createElement("input");
tempInput.value = window.location.href;
document.body.appendChild(tempInput);
tempInput.select();
tempInput.setSelectionRange(0, 99999); // For mobile devices
document.execCommand('copy');
document.body.removeChild(tempInput);
this.querySelector(".share__option-text").textContent = "Copied"
})
}
});
// document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu"));
}
function toggleLikeElementVisibility(selector, show) {
document.querySelector(`.${selector}`).style.display = show ? "block" : "none";
}
function closeKebabMenu(){
document.getElementById("myDropdown").classList.toggle("show");
}