Course contentsShow
← TypeScript
Lesson 250 of 1,7966. FunctionsFree lesson

Optional Parameters with ?

How to mark parameters as optional using the ? syntax and understand their type becomes T | undefined.

Optional Parameters with ?

What you'll learn: How to make function parameters optional using ? so that callers can skip them without causing errors.

The Core Idea

In JavaScript, you can call a function without providing all its parameters — the missing ones simply become undefined. TypeScript normally requires you to pass all declared parameters, but you can mark specific parameters as optional using the ? symbol. This tells TypeScript: "it's okay if the caller doesn't provide this value."

Syntax and Type Behavior

When you mark a parameter as optional with ?, TypeScript automatically treats its type as a union with undefined:

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

greet("Alice");              // OK: greeting is undefined
greet("Bob", "Welcome");     // OK: greeting is "Welcome"

Behind the scenes, greeting?: string becomes greeting: string | undefined. You don't write the | undefined yourself — TypeScript adds it automatically.

Think of It Like a Restaurant Menu

Optional parameters are like "sides" on a menu. The main dish is required, but you can order it with or without fries. The kitchen handles both cases.

Important Rules

Optional parameters must come after required parameters. You can't make the first parameter optional and the second required — TypeScript enforces left-to-right ordering:

// ✅ Correct
function build(id: number, name?: string) {}

// ❌ Wrong: required after optional
// function build(id?: number, name: string) {}

Key Takeaway: Use ? after a parameter name to make it optional; TypeScript treats it as T | undefined, and optional parameters must come last in the parameter list.