Enhancing Flexibility and Immutability - Textnotes

Enhancing Flexibility and Immutability


Learn how to use optional and readonly properties in TypeScript to create flexible and immutable objects. This module explains optional properties, readonly properties, and immutability concepts with practical examples.

1. Optional Properties

Optional properties allow an object to include properties that may or may not be present. They are defined using a question mark (?) after the property name.

Basic Example


interface Employee {
id: number;
name: string;
department?: string; // Optional property
}

let emp1: Employee = { id: 101, name: "Muni" };
let emp2: Employee = { id: 102, name: "Ravi", department: "HR" };

Optional properties provide flexibility when some data is not always required, such as partial updates or optional configuration settings.

2. Readonly Properties

Readonly properties prevent modification of a property after the object is created. They are defined using the readonly keyword.

Basic Example


interface Config {
readonly apiUrl: string;
timeout: number;
}

let config: Config = { apiUrl: "https://api.example.com", timeout: 5000 };

// config.apiUrl = "https://api.newurl.com"; // Error
config.timeout = 10000; // Allowed

Readonly properties are useful for constants, configuration objects, and data that should not change at runtime.

Readonly Arrays


let numbers: readonly number[] = [1, 2, 3];

// numbers.push(4); // Error

Readonly arrays enforce immutability and prevent accidental changes to data structures.

3. Immutability Concepts

Immutability refers to the principle of not changing an object after it is created. TypeScript provides features like readonly and ReadonlyArray to support immutability.

Benefits of Immutability

  1. Prevents accidental data changes
  2. Improves code predictability
  3. Simplifies debugging
  4. Enhances functional programming patterns

Example with Nested Objects


interface User {
readonly id: number;
name: string;
readonly address: {
city: string;
zip: string;
};
}

let user: User = {
id: 1,
name: "Muni",
address: { city: "Mumbai", zip: "400001" }
};

// user.id = 2; // Error
// user.address = { city: "Pune", zip: "411001" }; // Error
user.name = "Ravi"; // Allowed

By using readonly at multiple levels, you can enforce immutability in critical parts of your data structures.

Conclusion

Optional and readonly properties in TypeScript provide flexibility and immutability in object design. Optional properties make objects adaptable, while readonly properties ensure critical data cannot be modified, leading to safer and more predictable applications.