Type System

Typed Functions

Add type annotations to function parameters and return values for safer, more predictable code.

Function Type Annotations

TypeScript lets you specify the types of both parameters and return values. This catches errors when you call a function with wrong arguments or use the return value incorrectly.

Optional and Default Parameters

Use ? for optional parameters. Default values also make parameters optional.

Function Overloads

TypeScript supports multiple function signatures for the same function — useful when a function behaves differently depending on argument types.

Generic Functions

Generics allow functions to work with multiple types while preserving type safety.

Example

typescript
// Basic function types
function greet(name: string): string {
  return `Hello, ${name}!`;
}

// Arrow function with types
const multiply = (a: number, b: number): number => a * b;

// Optional parameters
function createUser(name: string, age?: number): object {
  return { name, age: age ?? 'unknown' };
}

// Default parameters
function power(base: number, exponent: number = 2): number {
  return Math.pow(base, exponent);
}

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

// Generic functions
function first<T>(arr: T[]): T | undefined {
  return arr[0];
}

const firstNum = first([1, 2, 3]);       // type: number | undefined
const firstStr = first(["a", "b", "c"]); // type: string | undefined

// Function type as parameter (callback)
function processItems<T>(
  items: T[],
  callback: (item: T, index: number) => void
): void {
  items.forEach(callback);
}

processItems([1, 2, 3], (num, i) => console.log(i, num));

// Return type void
function logMessage(message: string): void {
  console.log(message);
}
Try it yourself — TYPESCRIPT