TypeScript Lesson 4: Functions

📘 TypeScript CourseLesson 4 of 12 · 33% complete

Functions in TypeScript have typed parameters and return types. This is where TypeScript catches the most bugs in real code.

Function Types

// Parameter types + return type
function add(a: number, b: number): number {
  return a + b;
}

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

// Optional parameter (may be undefined)
function greet(name: string, title?: string): string {
  if (title) return `Hello, ${title} ${name}`;
  return `Hello, ${name}`;
}
greet("Alice");         // OK
greet("Alice", "Dr."); // OK

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

Function Types as Values

// Type a function that takes two numbers and returns number
type MathFn = (a: number, b: number) => number;

const add: MathFn = (a, b) => a + b;
const sub: MathFn = (a, b) => a - b;

function operate(a: number, b: number, fn: MathFn): number {
  return fn(a, b);
}

operate(10, 5, add); // 15
operate(10, 5, sub); // 5

Rest Parameters and Overloads

// Rest: variable number of arguments
function sum(...nums: number[]): number {
  return nums.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3, 4, 5); // 15

// Overloads: one function, different signatures
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);
}

🏋️ Practice Task

Create a typed utility library: clamp(value, min, max) → clamps number to range. capitalize(str) → string. repeat(str, times?) → string (default 3). pipe(…fns: Function[]) → applies functions in sequence. All fully typed.

💡 Hint: For pipe: type Transform = (input: any) => any. pipe(…fns: Transform[]) uses reduce to apply each.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *