T

Erweiterte Typen

TypeScript Syntax Guide

Union, Intersection, Type Aliases und Literal Types

Erweiterte Typen

Union, Intersection, Type Aliases und Literal Types

TypeScript erweiterte typen (typescript)
        
          // Union types
type StringOrNumber = string | number;

function formatValue(value: StringOrNumber): string {
  if (typeof value === "string") {
    return value.toUpperCase();
  }
  return value.toFixed(2);
}

// Discriminated unions
interface Square {
  kind: "square";
  size: number;
}

interface Rectangle {
  kind: "rectangle";
  width: number;
  height: number;
}

interface Circle {
  kind: "circle";
  radius: number;
}

type Shape = Square | Rectangle | Circle;

function getArea(shape: Shape): number {
  switch (shape.kind) {
    case "square":
      return shape.size ** 2;
    case "rectangle":
      return shape.width * shape.height;
    case "circle":
      return Math.PI * shape.radius ** 2;
  }
}

// Intersection types
type Name = { name: string };
type Age = { age: number };
type Person = Name & Age; // Must have both name and age

const person: Person = {
  name: "John",
  age: 25
};

// Type guards
function isString(value: unknown): value is string {
  return typeof value === "string";
}

function isShape(obj: any): obj is Shape {
  return obj && typeof obj.kind === "string";
}

// Using type guards
function processValue(value: unknown): string {
  if (isString(value)) {
    return value.toUpperCase(); // TypeScript knows value is string
  }
  return "Not a string";
}

// keyof operator
type PersonKeys = keyof Person; // "name" | "age"

// Indexed access types
type PersonName = Person["name"]; // string

// typeof operator for types
const config = {
  apiUrl: "https://api.example.com",
  timeout: 5000
};

type Config = typeof config;

// Mapped types with template literals
type EventHandlers<T extends string> = {
  [K in T as `on${Capitalize<K>}`]: () => void;
};

type ButtonEvents = EventHandlers<'click' | 'hover'>;
// Results in: { onClick: () => void; onHover: () => void; }

// Never type
function throwError(message: string): never {
  throw new Error(message);
}

// Exhaustive checking with never
function assertNever(value: never): never {
  throw new Error(`Unexpected value: ${value}`);
}

function handleShape(shape: Shape) {
  switch (shape.kind) {
    case "square":
      return shape.size;
    case "rectangle":
      return shape.width;
    case "circle":
      return shape.radius;
    default:
      return assertNever(shape); // Ensures all cases are handled
  }
}
        
      

Explanation

TypeScript bietet erweiterte Typ-Features wie Union Types (ein Wert kann einer von mehreren Typen sein), Intersection Types (Kombination mehrerer Typen zu einem), Type Aliases (einem Typ einen neuen Namen geben) und Literal Types (eine Variable auf spezifische String-, Zahlen- oder Boolean-Werte beschränken).

Common Use Cases

  • Erstellen flexibler Funktionsparameter
  • Kombinieren von Interfaces
  • Definieren benutzerdefinierter Typnamen für komplexe Typen
  • Erzwingen spezifischer Werte für Variablen

Related TypeScript Syntax

Master Erweiterte Typen in TypeScript

Understanding Erweiterte Typen is fundamental to writing clean and efficient TypeScript code. This comprehensive guide provides you with practical examples and detailed explanations to help you master this important concept.

Whether you're a beginner learning the basics or an experienced developer looking to refresh your knowledge, our examples cover real-world scenarios and best practices for using Erweiterte Typen effectively in your TypeScript projects.

Key Takeaways

  • Erstellen flexibler Funktionsparameter
  • Kombinieren von Interfaces
  • Definieren benutzerdefinierter Typnamen für komplexe Typen