Object Property Modifiers


Object Property Modifiers#
TypeScript provides several property modifiers to control how object properties behave. These modifiers help you create more precise and safer type definitions.
Optional Properties
Mark properties as optional using the ? modifier. This allows objects to omit those properties:
interface User {
name: string;
email?: string; // optional
}
const user1: User = { name: "Alice" }; // Valid
const user2: User = { name: "Bob", email: "[email protected]" }; // Also validOptional properties are useful when some data might not be available.
Readonly Properties
Use the readonly modifier to prevent properties from being modified after initialization:
interface Config {
readonly apiKey: string;
readonly timeout: number;
}
const config: Config = { apiKey: "secret123", timeout: 5000 };
// config.apiKey = "newkey"; // Error: Cannot assign to 'apiKey' because it is a read-only propertyReadonly properties help enforce immutability and prevent accidental changes.
Required Properties
By default, properties in interfaces are required. You can also explicitly make optional properties required using utility types:
interface PartialUser {
name?: string;
email?: string;
}
// Make all properties required
type CompleteUser = Required<PartialUser>;
const user: CompleteUser = { name: "Alice", email: "[email protected]" };Utility Types for Modifiers
TypeScript provides utility types to manipulate property modifiers:
Partial<T>: Makes all properties optionalRequired<T>: Makes all properties requiredReadonly<T>: Makes all properties readonlyPick<T, K>: Selects specific propertiesOmit<T, K>: Excludes specific properties
Example:
interface Product {
id: number;
name: string;
price: number;
description?: string;
}
// All properties optional
type PartialProduct = Partial<Product>;
// All properties readonly
type ReadonlyProduct = Readonly<Product>;Best Practices
- Use optional properties for data that may not always be present
- Apply readonly to properties that should not change after initialization
- Leverage utility types to transform property modifiers as needed
- Be consistent in your use of modifiers across your codebase
Tip: Combine modifiers like readonly and ? for
fine-grained control: readonly name?: string
Common Mistakes
- Forgetting that optional properties can still be
undefined - Attempting to modify readonly properties at runtime
- Overusing optional properties, leading to less predictable code
- Not leveraging utility types for common modifier transformations
Next Steps
Next, dive into index signatures to handle objects with dynamic keys and create flexible dictionary-like structures.