Meistern Sie fortgeschrittene TypeScript-Typen: Generics, Utility Types, Conditional Types und Type Guards. Vollständige Anleitung für typsichere Entwicklung.
# TypeScript Fortgeschrittene Typen
Lernen Sie fortgeschrittene TypeScript-Konzepte für robuste und typsichere Anwendungen.
## Generics (Generische Typen)
```typescript
// Generische Funktion
function ersteElement<T>(array: T[]): T | undefined {
return array[0];
}
const zahlen = ersteElement([1, 2, 3]); // Typ: number
const texte = ersteElement(["a", "b"]); // Typ: string
// Generische Schnittstelle
interface ApiAntwort<T> {
daten: T;
erfolg: boolean;
nachricht?: string;
zeitstempel: Date;
}
interface Benutzer {
id: string;
name: string;
email: string;
}
async function holeBenutzer(id: string): Promise<ApiAntwort<Benutzer>> {
const antwort = await fetch(`/api/benutzer/${id}`);
return antwort.json();
}
```
## Utility Types (Hilfstypen)
```typescript
interface Produkt {
id: string;
name: string;
preis: number;
beschreibung: string;
lagerbestand: number;
erstelltAm: Date;
}
// Partial - Alle Eigenschaften optional
type ProduktAktualisierung = Partial<Produkt>;
// Pick - Nur bestimmte Eigenschaften
type ProduktVorschau = Pick<Produkt, "id" | "name" | "preis">;
// Omit - Bestimmte Eigenschaften ausschließen
type NeuesProdukt = Omit<Produkt, "id" | "erstelltAm">;
// Required - Alle Eigenschaften erforderlich
type VollständigesProdukt = Required<Produkt>;
// Readonly - Alle Eigenschaften nur lesbar
type UnveränderlichesProdukt = Readonly<Produkt>;
// Record - Objekttyp mit bestimmten Schlüsseln
type ProduktKatalog = Record<string, Produkt>;
```
## Conditional Types (Bedingte Typen)
```typescript
// Einfacher bedingter Typ
type IstString<T> = T extends string ? true : false;
type Test1 = IstString<string>; // true
type Test2 = IstString<number>; // false
// Extraktion von Array-Elementtypen
type ArrayElement<T> = T extends (infer E)[] ? E : never;
type ZahlenElement = ArrayElement<number[]>; // number
// Funktion Rückgabetyp extrahieren
type RückgabeTyp<T> = T extends (...args: any[]) => infer R ? R : never;
function holeZahl(): number {
return 42;
}
type Ergebnis = RückgabeTyp<typeof holeZahl>; // number
```
## Type Guards (Typwächter)
```typescript
interface Hund {
art: "hund";
bellen: () => void;
}
interface Katze {
art: "katze";
miauen: () => void;
}
type Haustier = Hund | Katze;
// Typwächter-Funktion
function istHund(tier: Haustier): tier is Hund {
return tier.art === "hund";
}
function tierGeräusch(tier: Haustier) {
if (istHund(tier)) {
tier.bellen(); // TypeScript weiß, dass tier ein Hund ist
} else {
tier.miauen(); // TypeScript weiß, dass tier eine Katze ist
}
}
// Assertion-Funktion
function assertIstString(wert: unknown): asserts wert is string {
if (typeof wert !== "string") {
throw new Error("Wert muss ein String sein");
}
}
```
## Mapped Types (Abgebildete Typen)
```typescript
interface Formular {
benutzername: string;
email: string;
passwort: string;
}
// Alle Felder nullable machen
type Nullable<T> = {
[K in keyof T]: T[K] | null;
};
type NullbaresFormular = Nullable<Formular>;
// Felder mit Getter-Funktionen
type Getter<T> = {
[K in keyof T as `hole${Capitalize<string & K>}`]: () => T[K];
};
type FormularGetter = Getter<Formular>;
// { holeBenutzername: () => string; holeEmail: () => string; ... }
```
Diese Anleitung hilft deutschen Entwicklern, TypeScript-Typen vollständig zu verstehen.This typescript prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their typescript implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For typescript projects, consider mentioning your framework version, coding style, and any specific libraries you're using.