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?