Start Coding

Topics

Readonly Properties in TypeScript

TypeScript's readonly properties provide a powerful way to create immutable object properties. They enhance code safety and clarity by preventing accidental modifications to values that should remain constant.

What are Readonly Properties?

Readonly properties are object properties that can only be assigned a value when an object is first created. After initialization, these properties cannot be changed. This immutability helps prevent bugs and makes code more predictable.

Syntax and Usage

To declare a readonly property, use the readonly keyword before the property name in an interface or class declaration. Here's a simple example:


interface Point {
    readonly x: number;
    readonly y: number;
}

let p1: Point = { x: 10, y: 20 };
// p1.x = 5; // Error: Cannot assign to 'x' because it is a read-only property.
    

In this example, x and y are readonly properties. Once set, they cannot be modified.

Readonly Properties in Classes

Readonly properties can also be used in classes. They're particularly useful for properties that should be set only once, typically in the constructor:


class Circle {
    readonly radius: number;

    constructor(radius: number) {
        this.radius = radius;
    }

    // circumference() method can use radius, but can't modify it
    circumference(): number {
        return 2 * Math.PI * this.radius;
    }
}

const circle = new Circle(5);
console.log(circle.radius); // 5
// circle.radius = 10; // Error: Cannot assign to 'radius' because it is a read-only property.
    

Benefits of Readonly Properties

  • Improved code safety by preventing accidental modifications
  • Clear indication of which properties should not change after initialization
  • Better alignment with functional programming principles
  • Enhanced type checking and IDE support

Readonly Arrays and Objects

TypeScript also provides utility types for creating readonly versions of arrays and objects:


const numbers: ReadonlyArray<number> = [1, 2, 3, 4];
// numbers.push(5); // Error: Property 'push' does not exist on type 'readonly number[]'.

const person: Readonly<{ name: string; age: number }> = { name: "Alice", age: 30 };
// person.age = 31; // Error: Cannot assign to 'age' because it is a read-only property.
    

These utility types provide an additional layer of immutability to your data structures.

Best Practices

  • Use readonly properties for values that should not change after initialization
  • Consider using readonly properties for function parameters to indicate they won't be modified
  • Combine readonly properties with const assertions for maximum immutability
  • Be aware that readonly is enforced only at compile-time, not at runtime

Related Concepts

To deepen your understanding of TypeScript's type system and immutability features, explore these related topics:

By mastering readonly properties and related concepts, you'll be able to write more robust and maintainable TypeScript code, leveraging the language's powerful type system to prevent errors and improve code quality.