Static and Readonly Properties

1. Welcome and Icebreaker:

  • If you could make any rule in your life unchangeable (readonly) or shared by everyone (static), what would it be?

2. Outline the Session:

  • We’ll learn about static and readonly properties in TypeScript classes.
  • Learning Outcomes: Understand how to use static for class-level properties/methods and readonly for immutable properties.
  • Let’s make some things unchangeable and shared!

3. Concept Explanation:

  • Static Properties/Methods: Declared with the static keyword. Belong to the class, not instances. Accessed as ClassName.property.
  • Readonly Properties: Declared with the readonly keyword. Can only be assigned once (at declaration or in the constructor).
  • Use static for constants or utility methods; use readonly for values that shouldn’t change after initialization.

4. Live Coding Demonstration:

class Counter {
  static count = 0;
  readonly id: number;
  constructor(id: number) {
    this.id = id;
    Counter.count++;
  }
  static reset() {
    Counter.count = 0;
  }
}

const c1 = new Counter(1);
const c2 = new Counter(2);
console.log(Counter.count); // 2
console.log(c1.id); // 1
// c1.id = 10; // Error: Cannot assign to 'id' because it is a read-only property.
Counter.reset();
console.log(Counter.count); // 0

5. Tasks:

  • Short Exercise:
    1. Create a class AppConfig with a static property version (string) and a readonly property appName (string).
    2. Add a static method to print the version.
    3. Create an instance of AppConfig and print its appName.
    4. Try to change the appName and observe the error.