Optional Properties in Classes
What you'll learn: How to mark class properties as optional with ? so they can remain undefined without requiring initialization.
The Problem
In TypeScript classes, every property you declare must be initialized—either inline, in the constructor, or with a definite assignment assertion. But sometimes you genuinely want a property that might not have a value right away.
Optional Properties with ?
Just like in object types and interfaces, you can mark class properties as optional using the ? operator. This tells TypeScript: "This property might not have a value, and that's okay."
class User {
name: string;
email?: string; // Optional property
age?: number; // Optional property
constructor(name: string) {
this.name = name;
// No need to initialize email or age!
}
}
const user = new User("Alice");
console.log(user.email); // undefined (no error)
Type Safety with Optional Properties
When you access an optional property, TypeScript knows it might be undefined, so you'll need to handle that possibility:
class Product {
name: string;
discount?: number;
constructor(name: string) {
this.name = name;
}
getPrice(basePrice: number): number {
// TypeScript knows discount might be undefined
if (this.discount) {
return basePrice * (1 - this.discount);
}
return basePrice;
}
}
Optional vs Definite Assignment Assertion
These solve different problems:
- Optional
?: Property type isstring | undefined— it's meant to sometimes be undefined - Definite assertion
!: Property type isstring— you promise it will be assigned, just not in a way TypeScript can verify
Key Takeaway: Use ? on class properties when they're legitimately optional—this allows undefined values and skips initialization requirements while maintaining type safety through union with undefined.