• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Understanding Generics in TypeScript: The Ultimate Guide to Reusable Code

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
? What Are Generics in TypeScript?


When developing applications, we often need flexibility while maintaining type safety. TypeScript’s Generics solve this challenge by allowing us to create reusable components that can work with multiple data types.

In this guide, we’ll break down generics step by step, ensuring you fully understand how to use them efficiently.

? Why Should You Learn Generics?


Without generics, you would need separate functions for different data types. For example:


function returnString(value: string): string {
return value;
}

function returnNumber(value: number): number {
return value;
}

This approach leads to redundant code. Generics solve this problem by creating a single function that works for all types.

? Understanding Generics with a Simple Example


Generics use a placeholder type, such as <T>, allowing a function to handle various data types dynamically.


function returnValue<T>(value: T): T {
return value;
}

Now, this function works for any type:


console.log(returnValue<string>("Hello Generics!")); // "Hello Generics!"
console.log(returnValue<number>(123)); // 123
console.log(returnValue<boolean>(true)); // true
console.log(returnValue<object>({ name: "TypeScript" })); // { name: "TypeScript" }

This is the power of generics — one function that adapts to different types while maintaining type safety.

?️ Applying Generics in Classes


If you’re working with data storage, you can use generics in a class to make it flexible yet secure:


class Storage<T> {
private item: T;

setItem(value: T) {
this.item = value;
}

getItem(): T {
return this.item;
}
}

// Using the class with different types
const stringStorage = new Storage<string>();
stringStorage.setItem("Understanding Generics is fun!");
console.log(stringStorage.getItem()); // "Understanding Generics is fun!"

const numberStorage = new Storage<number>();
numberStorage.setItem(42);
console.log(numberStorage.getItem()); // 42

Since Generics preserve type integrity, you won’t accidentally store numbers in a string container.

? Generics in Interfaces for Flexible Object Type


You can apply generics in interfaces to create highly adaptable structures.


interface User<T> {
id: number;
data: T;
}

const user1: User<string> = { id: 1, data: "Admin" };
const user2: User<number[]> = { id: 2, data: [10, 20, 30] };

console.log(user1); // { id: 1, data: "Admin" }
console.log(user2); // { id: 2, data: [10, 20, 30] }

Here, data can be any type, making the interface highly reusable.

? Adding Constraints to Generic


If you want **restrictions **on the generic type, use extends:


function getLength<T extends { length: number }>(item: T): number {
return item.length;
}

console.log(getLength("Understanding Generics")); // ✅ Works (strings have `.length`)
console.log(getLength([1, 2, 3])); // ✅ Works (arrays have `.length`)
console.log(getLength({ length: 10 })); // ✅ Works (objects with length are allowed)

Here, T extends { length: number } ensures that only values with a .length property are accepted.

? Benefits of Generics in TypeScript

  1. Write Less Code — One function or class for multiple types.
  2. Increase Flexibility — Works with different data types while enforcing type safety.
  3. Improve Maintainability — No need to refactor when adding new types.
  4. Future-Proof Applications — Generics scale easily as your codebase grows. Generics are essential in TypeScript and make your code efficient, clean, and reusable.
? Final Challenge: Try Generics Yourself


Want to test your understanding of generics? Try writing a generic function that adds two values — it should work for both numbers and strings! Drop your solution in the comments below.

??‍♂ Explore my portfolio ✨
This is where innovation meets expertise ✨ — a carefully crafted showcase of my

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

. Dive into a world where each project tells its own story of challenges conquered ? and solutions crafted ?️. While my portfolio demonstrates technical prowess ?, it also reflects my passion for pushing boundaries ? and thinking beyond conventional limits ?. Ready to connect? ?

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

for the full story of my professional adventure, and let’s explore potential collaborations. Together, we might just create something extraordinary ?.

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу