#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
3 min read
Question 8 of 48easy

What are Optional Properties in TypeScript?

Making properties optional with ?.

What You'll Learn

  • Optional property syntax
  • Optional parameters
  • Optional chaining

Optional Properties

Use ? to mark a property as optional.

code.tsTypeScript
interface User {
  name: string;
  email: string;
  phone?: string; // Optional
}

const user1: User = {
  name: "John",
  email: "john@example.com"
  // phone is optional, can be omitted
};

const user2: User = {
  name: "Jane",
  email: "jane@example.com",
  phone: "123-456-7890"
};

Optional Function Parameters

code.tsTypeScript
function greet(name: string, greeting?: string) {
  return `${greeting || "Hello"}, ${name}!`;
}

greet("John");          // "Hello, John!"
greet("John", "Hi");    // "Hi, John!"

Optional Chaining

code.tsTypeScript
interface Company {
  name: string;
  address?: {
    city?: string;
  };
}

const company: Company = { name: "Acme" };

// Safe access with ?.
console.log(company.address?.city); // undefined (no error)