Lesson 6 of 15

Optional Properties

Optional Properties

Mark a property optional with ?. It can be omitted when creating the object:

interface User {
    name: string;
    email: string;
    age?: number;      // optional
    admin?: boolean;   // optional
}

const u1: User = { name: "Alice", email: "alice@example.com" };
const u2: User = { name: "Bob", email: "bob@example.com", age: 30 };

Inside the function, optional properties have type T | undefined. You must check before using:

function greetUser(u: User): string {
    const suffix = u.age !== undefined ? " (age " + u.age + ")" : "";
    return "Hello, " + u.name + suffix;
}

Optional Parameters

Function parameters can also be optional:

function repeat(s: string, times?: number): string {
    const n = times !== undefined ? times : 1;
    return s.repeat(n);
}

console.log(repeat("ha"));      // ha
console.log(repeat("ha", 3));   // hahaha

Your Task

Write function formatName(first: string, last?: string): string that returns:

  • first + " " + last if last is provided
  • Just first if last is omitted
TypeScript loading...
Loading...
Click "Run" to execute your code.