TypeScript Readonly and Static

TypeScript readonly and static keywords are used to modify the behavior of properties and methods.

Readonly in Typescript

If we mark any property or member as readonly in typescript, the value for that member cannot be changed further. We can only read the value assigned and cannot modify or update.

Let’s take an example of a Student class:

class Student {
    readonly Id: number;
    Name: string;
    
    constructor(id: number, name: string) {
        this.Id = id;
        this.Name = name;
    }
}

let student = new Student(1, "DS");
student.Id = 2; //Compile-time Error as the property is readonly
student.Name = "Bob"; //Works fine

Since Id is marked as readonly, it can be initialized at the time of declaration or in the constructor.

If we try to change the value of the Id field, it gives us a compile-time error.

error TS2540: Cannot assign to Id’ because it is a constant or a read-only property.

👉 An interface can also have readonly member properties.

Static in Typescript

When we mark a member or method as static in typescript, it gets available at the class level and not the instance level.

The static members of a class are accessed using <ClassName>.<StaticMember> without creating an object of a class.

Let’s take the example of a Circle class:

class Circle {
    static pi: number = 3.14;
    
    static areaOfCircle(radius:number) {
        return (this.pi * radius * radius);
    }
}

console.log(Circle.pi); // returns 3.14
console.log(Circle.calculateArea(10)); // returns 314

Here, variable pi and method areaOfCricle are marked as static. They are available at the class level and are accessed using className.MemberName.

👉 The class or constructor cannot be static in TypeScript.