Declare ReadOnly Members in TypeScript

In TypeScript, you can declare members of a class as readonly, which means that their values cannot be changed once they are set. In this lesson, we’ll go over how to declare readonly members in TypeScript with a code example.

Declaring Readonly Properties

To declare a readonly property in a class, you use the readonly keyword before the property name. Here’s an example:

class MyClass {
  readonly myReadonlyProperty = 'Hello';

  constructor() {
    // constructor code here
  }
}

In this example, we declare a readonly property myReadonlyProperty with the value of 'Hello'. This property cannot be changed once it is set. If you try to change it, you’ll get a compilation error:

const myInstance = new MyClass();
myInstance.myReadonlyProperty = 'World'; // Error: Cannot assign to 'myReadonlyProperty' because it is a read-only property.

Readonly Parameters

You can also declare function parameters as readonly. This is useful when you want to ensure that a function doesn’t modify its input arguments. Here’s an example:

function printArray(arr: readonly string[]) {
  for (const item of arr) {
    console.log(item);
  }
}

In this example, we declare the arr parameter as readonly. This ensures that the function printArray cannot modify the contents of the array passed as an argument. If we try to modify the array, we’ll get a compilation error:

const myArray = ['Hello', 'World'];
printArray(myArray);
myArray[0] = 'Goodbye'; // Error: Index signature in type 'readonly string[]' only permits reading.

Conclusion

In conclusion, declaring members as readonly in TypeScript can be a useful way to ensure that their values cannot be changed once they are set. This can help prevent bugs and make your code more reliable. You can use the readonly keyword to declare readonly properties and readonly function parameters.