Using readonly in TypeScript: Ensuring Immutability and Data Integrity
Learn how the readonly keyword in TypeScript enforces immutability, ensuring that property values cannot be modified after assignment. Explore its use in class properties, interfaces, and type aliases to maintain data integrity and enhance code reliability.
TypeScript Readonly
The readonly
keyword in TypeScript guarantees that a property's value cannot be modified after it's assigned. This is crucial for maintaining data integrity and preventing accidental modifications. By using readonly
, you create immutable properties, enhancing code reliability and predictability.
When to Use readonly
- Class properties: Prevent accidental changes to object properties.
- Interface properties: Define contracts where properties should not be mutable.
- Type aliases: Create read-only versions of existing types.
Examples
Syntax
class Person {
readonly firstName: string;
readonly lastName: string;
constructor(firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
}
}
Output
No direct output for this example.
Syntax
interface User {
readonly id: number;
email: string;
}
Output
No direct output for this example.
Syntax
type ImmutablePoint = Readonly<{ x: number; y: number }>;
Output
No direct output for this example.
Deep Readonly
While readonly
prevents direct modification of properties, it doesn't prevent modifications to nested objects. To create deeply immutable objects, use the DeepReadonly
utility type:
Syntax
import { DeepReadonly } from 'typescript';
interface Address {
street: string;
city: string;
}
interface User {
name: string;
address: Address;
}
const user: DeepReadonly = {
name: 'John Doe',
address: { street: '123 Main St', city: 'Anytown' }
};
// user.name = 'Jane Doe'; // Error
// user.address.street = '456 Elm St'; // Error
Output
No direct output for this example.
Additional Considerations
- Initialization:
readonly
properties must be initialized either at declaration or within the constructor. - Compile-Time Enforcement: TypeScript's type system enforces
readonly
restrictions at compile time. - Runtime Behavior: While TypeScript prevents compile-time errors, it's essential to remember that
readonly
is a compile-time construct. JavaScript itself doesn't have areadonly
concept.