TypeScript Course
TypeScript
/
Beginner

Optional Properties

Definition

Using a question mark `?` after a property name in an object type or interface to indicate that the property is not strictly required.

Explain Like I'm New

Imagine filling out a form online. Your 'Name' and 'Email' are required (no question mark). 'Phone Number' is optional. If you don't provide it, the form still successfully submits. Optional properties allow an object to be valid even if pieces are missing.

Real World Example

Typing a generic `ButtonProps` interface in React. The `onClick` handler is required, but the `className` string is optional.

Common Use Cases

  • •React component props
  • •Partial API update payloads (PATCH requests)

Interactive Example

interface UserProfile {
  name: string;        // Required
  email: string;       // Required
  phoneNumber?: string; // Optional!
}

// Valid!
const user1: UserProfile = {
  name: "Alice",
  email: "alice@test.com"
};

// Also Valid!
const user2: UserProfile = {
  name: "Bob",
  email: "bob@test.com",
  phoneNumber: "555-1234"
};

Interview Questions

basic

  • How do you mark a property as optional?

intermediate

  • What is the type of an optional property if it is not provided?

advanced

  • What is the `exactOptionalPropertyTypes` compiler option?

Flash Cards

Question

What is the type if not provided?

Click to reveal answer
Answer

It is intrinsically `undefined`. If you have `age?: number`, TS treats its type internally as `number | undefined`. You must handle the `undefined` case in your logic.

Question

What is exactOptionalPropertyTypes?

Click to reveal answer
Answer

By default, TS allows you to explicitly assign `undefined` to an optional property (`age: undefined`). If this strict flag is turned on in `tsconfig.json`, you are NOT allowed to explicitly set it to undefined; you must either omit the key entirely, or provide a real number.