T

Typisierte Funktionen

TypeScript Syntax Guide

Funktionstypisierung und Überladungen in TypeScript

Typisierte Funktionen

Funktionstypisierung und Überladungen in TypeScript

TypeScript typisierte funktionen (typescript)
        
          // Function type annotation
function greet(name: string): string {
  return `Hello, ${name}!`;
}

// Arrow function with types
const greetArrow = (name: string): string => `Hello, ${name}!`;

// Optional parameters
function createUser(name: string, age?: number): User {
  return {
    id: Math.random(),
    name,
    createdAt: new Date(),
    ...(age && { age })
  };
}

// Default parameters
function multiply(a: number, b: number = 2): number {
  return a * b;
}

// Rest parameters
function sum(...numbers: number[]): number {
  return numbers.reduce((a, b) => a + b, 0);
}

// Function overloads
function format(value: string): string;
function format(value: number): string;
function format(value: string | number): string {
  if (typeof value === "string") {
    return value.toUpperCase();
  }
  return value.toFixed(2);
}

// Generic functions
function identity<T>(value: T): T {
  return value;
}

function mapArray<T, U>(arr: T[], mapper: (item: T) => U): U[] {
  return arr.map(mapper);
}

// Usage
const result1 = identity<string>("hello");
const result2 = identity(42);

const numbers = [1, 2, 3];
const strings = mapArray(numbers, n => n.toString());
        
      

Explanation

TypeScript ermöglicht das Tippen von Funktionsparametern und Rückgabewerten. Funktionsüberladungen bieten mehrere Aufrufsignaturen, während Generics wiederverwendbare typsichere Funktionen ermöglichen.

Common Use Cases

  • Typsichere APIs
  • Bessere Dokumentation
  • Kompilierzeit-Fehlerprüfung
  • IntelliSense-Unterstützung

Related TypeScript Syntax

Master Typisierte Funktionen in TypeScript

Understanding Typisierte Funktionen 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 Typisierte Funktionen effectively in your TypeScript projects.

Key Takeaways

  • Typsichere APIs
  • Bessere Dokumentation
  • Kompilierzeit-Fehlerprüfung