S SmartDocs
시리즈: Typescript typescript 100 줄 · 업데이트 2026-01-04

04-functions.ts

Typescript/src/01-beginner/04-functions.ts

// ============================================
// 04. Functions
// ============================================

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

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

// Optional Parameters
function greetWithTitle(name: string, title?: string): string {
  if (title) {
    return `Hello, ${title} ${name}!`;
  }
  return `Hello, ${name}!`;
}

console.log(greetWithTitle("Alice"));              // "Hello, Alice!"
console.log(greetWithTitle("Alice", "Dr."));       // "Hello, Dr. Alice!"

// Default Parameters
function greetWithDefault(name: string, greeting: string = "Hello"): string {
  return `${greeting}, ${name}!`;
}

console.log(greetWithDefault("Alice"));                    // "Hello, Alice!"
console.log(greetWithDefault("Alice", "Hi"));              // "Hi, Alice!"

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

console.log(sum(1, 2, 3));        // 6
console.log(sum(1, 2, 3, 4, 5));  // 15

// Arrow Functions
const multiply = (x: number, y: number): number => x * y;

const greetArrow = (name: string): string => {
  const message = `Hello, ${name}!`;
  return message;
};

// Function Types
let myFunction: (a: number, b: number) => number;

myFunction = function(x: number, y: number): number {
  return x + y;
};

// Type Aliases for Functions
type MathOperation = (a: number, b: number) => number;

const addOp: MathOperation = (a, b) => a + b;
const multiplyOp: MathOperation = (a, b) => a * b;

// Function Overloads
function process(value: string): string;
function process(value: number): number;
function process(value: boolean): boolean;
function process(value: string | number | boolean): string | number | boolean;
function process(value: string | number | boolean): string | number | boolean {
  if (typeof value === "string") {
    return value.toUpperCase();
  } else if (typeof value === "number") {
    return value * 2;
  } else {
    return !value;
  }
}

console.log(process("hello"));  // "HELLO"
console.log(process(5));        // 10
console.log(process(true));     // false

// Return Types
function getAge(): number {
  return 25;
}

function getName(): string {
  return "Alice";
}

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

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

export { greet, add, sum, multiply, process };

관련 글