#typescript #beginner #functions

Day 6: Functions in TypeScript

Types in Functions

Welcome to Day 6! Functions are the workhorses of any application. Let’s make them safe.

Basic Typing

We can type the parameters and the return value.

function add(a: number, b: number): number {
  return a + b;
}

If you don’t return a number, TypeScript will complain.

Void

If a function doesn’t return anything (e.g., just logs to console), the return type is void.

function logMessage(message: string): void {
  console.log(message);
}

Optional Parameters

Just like objects, function parameters can be optional using ?.

function greet(name: string, greeting?: string): string {
  if (greeting) {
    return `${greeting}, ${name}!`;
  }
  return `Hello, ${name}!`;
}

greet("Jack"); // OK
greet("Jack", "Hi"); // OK

Default Parameters

You can provide default values. TypeScript infers the type from the default value.

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

Rest Parameters

Handling an unknown number of arguments.

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

sum(1, 2, 3, 4); // 10

Challenge for Today

  1. Write a function calculateDiscount that takes price (number) and isValid (boolean).
  2. If isValid is true, return the price * 0.9 (10% off). Otherwise return price.
  3. Add an optional argument discountAmount that overrides the 10% if provided.

See you on Day 7 for the final day of Phase 1!