🔧 AI Nachrichten Major AI platforms go down in unprecedented simultaneous outage(03.09.2026 um 17:34 Uhr)
🔧 AI Nachrichten ChatGPT, Claude, and Grok Down? Users Report Widespread Outages(03.09.2026 um 19:14 Uhr)
🔧 AI Nachrichten OpenAI Launches GPT-6 Astra, Says We May Have Entered the AGI Era(03.09.2026 um 22:08 Uhr)
🔧 AI Nachrichten Claude Comes to CarPlay as Fifth Major AI Chatbot App(05.09.2026 um 05:31 Uhr)
🔧 AI Nachrichten OpenAI’s GPT-6 Astra Is AGI, Says NVIDIA CEO Jensen Huang(07.09.2026 um 06:31 Uhr)
🔧 AI Nachrichten Blame AI companies for Mac mini and Mac Studio shortage(31.08.2026 um 10:32 Uhr)
🔧 AI Nachrichten Major AI platforms go down in unprecedented simultaneous outage(03.09.2026 um 17:34 Uhr)
🔧 AI Nachrichten ChatGPT, Claude, and Grok Down? Users Report Widespread Outages(03.09.2026 um 19:14 Uhr)
🔧 AI Nachrichten OpenAI Launches GPT-6 Astra, Says We May Have Entered the AGI Era(03.09.2026 um 22:08 Uhr)
🔧 AI Nachrichten Claude Comes to CarPlay as Fifth Major AI Chatbot App(05.09.2026 um 05:31 Uhr)
🔧 AI Nachrichten OpenAI’s GPT-6 Astra Is AGI, Says NVIDIA CEO Jensen Huang(07.09.2026 um 06:31 Uhr)
🔧 AI Nachrichten Blame AI companies for Mac mini and Mac Studio shortage(31.08.2026 um 10:32 Uhr)

🔧 Programmierung 🕛 kürzlich 3 Min Lesezeit
0

Understanding Generics in TypeScript: A Beginner’s Guide

↗ Quelle (dev.to)
🗣️ Stimme:
📑 Inhaltsübersicht

When creating applications, writing reusable and type-safe code is important. TypeScript offers Generics, which allow us to write code that works with multiple types while maintaining strong typing. This makes our code flexible and robust. In this blog, I’ll explain what generics are, why they’re useful, and how you can use them. 🚀









What Are Generics? 🧩



Generics in TypeScript let you create reusable components that can work with any data type. You don’t need to write multiple versions of the same code for different types. Instead, you can use a placeholder for the type and specify the actual type when using the code.









Why Use Generics? 🤔





  1. Reusability: Write one function or class and use it with any type. ♻️


  2. Type Safety: Catch errors during development, not at runtime. ✅


  3. Flexibility: Handle dynamic types without losing TypeScript’s benefits. 🌟









How Do Generics Work? ⚙️



Generics use type parameters as placeholders for types. These type parameters can be replaced with specific types when the function or class is used.



Here’s a simple example:




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







  • The <T> is the generic type parameter.

  • You can replace T with any type, and the function will return the same type it receives.









Examples of Using Generics 📚






1. Generic Functions 💡



Imagine you need a function that returns an array of any type:




CODE
function getArray<T>(items: T[]): T[] {
return items;
}

// Usage:
const numbers = getArray<number>([1, 2, 3]); // number[]
const strings = getArray<string>(["a", "b", "c"]); // string[]






This function works for both numbers and strings! 🎉









2. Generic Classes 📦



Generics are also useful in classes. For example:




CODE
class Box<T> {
private contents: T;

constructor(value: T) {
this.contents = value;
}

getContents(): T {
return this.contents;
}
}

// Usage:
const numberBox = new Box<number>(42);
const stringBox = new Box<string>("Hello");






Here, the Box class can store values of any type. 🛠️









3. Generic Interfaces 📝



You can define interfaces with generics to handle multiple types:




CODE
interface Pair<T, U> {
first: T;
second: U;
}

// Usage:
const pair: Pair<number, string> = { first: 1, second: "hello" };












4. Constraining Generics 🚧



Sometimes, you need to restrict what types a generic can accept:




CODE
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}

const person = { name: "John", age: 30 };
const name = getProperty(person, "name"); // Works
// const invalid = getProperty(person, "height"); // Error






Here, the key must be a property of the obj. 🔒









5. Default Type Parameters



You can assign a default type to a generic:




CODE
function createList<T = string>(): T[] {
return [];
}

// Usage:
const defaultList = createList(); // T defaults to string
const numberList = createList<number>(); // T is number












Why Generics Are Useful 🌟





  1. Prevents Code Duplication: You don’t need separate functions or classes for every type. ✂️


  2. Ensures Type Consistency: Generics help you enforce relationships between types. 🔗


  3. Improves Code Readability: The use of explicit type parameters makes your code clearer. 👓









Best Practices 🏆





  1. Use Descriptive Names: Instead of just T, use meaningful names like ItemType or KeyType. ✍️


  2. Rely on Inference: Let TypeScript infer the generic type whenever possible. 🔍


  3. Add Constraints: Use extends to limit the acceptable types for a generic. 🚦









Conclusion 🎯



Generics are an essential feature of TypeScript that make your code reusable, flexible, and safe. By understanding how to use them, you can write better and cleaner code for any project. If you’re just starting with generics, try simple examples first and gradually move on to more advanced use cases.



Got an idea where generics could help in your project? Let me know in the comments! 💬

Vollständiger Original-Bericht
Ausführliche Details, Code-Beispiele & Hersteller-Stellungnahme auf dev.to.
↗ Original-Artikel auf dev.to lesen
Wie bewertest du diesen Beitrag?
1 Klick Feedback
Teilen mit Netzwerk & Team:

Community-Analysen & Experten-Meinungen 0

Verfasse deine eigene Analyse, teile Workarounds oder diskutiere diesen Vorfall im Blog.
Noch keine Community-Analyse verfasst. Markiere einen Textabschnitt oder klicke oben auf Eigene Analyse verfassen“!
Community Pulse: Relevanz-Einschätzung
1 Klick Experten-Votum
🔴 Akute Relevanz 0%
🟡 In Evaluierung 0%
🟢 Keine Auswirkung 0%
Spannende Innovation 0%
Verwandte Story-Cluster & Quellen (Vektor-KI)
Port 8095 Engine
3 Quellen
GPT-6 Astra Release Today? OpenAI’s Next Major AI Model Is Almost Here
1 Quelle
Apple accuses OpenAI of destroying evidence as trade-secrets fight intensifies
1 Quelle
Major AI platforms go down in unprecedented simultaneous outage
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Understanding Generics in TypeScript: A Beginner’s Guide

Thematisch verwandte Begriffe: Understanding, Generics, TypeScript, Beginners · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...