Property Decorators

1. Welcome and Icebreaker:

  • If you could add a special label or behavior to any property you own, what would it be?

2. Outline the Session:

  • We’ll learn about property decorators in TypeScript: how to create and use them.
  • Learning Outcomes: Understand how to write decorators that add metadata or modify class properties.
  • Let’s label our properties!

3. Concept Explanation:

  • Property Decorators are functions applied to class properties.
  • They receive the target object and property name.
  • Can be used to add metadata, validation, or modify property behavior.
  • Syntax: @DecoratorName above a property.

4. Live Coding Demonstration:

function Readonly(target: any, propertyKey: string) {
  Object.defineProperty(target, propertyKey, {
    writable: false
  });
}

class User {
  @Readonly
  id: number = 1;
}

const user = new User();
// user.id = 2; // Error: Cannot assign to read only property
console.log(user.id);

5. Tasks:

  • Short Exercise:
    1. Write a property decorator that makes a property read-only.
    2. Write a decorator that adds metadata to a property.
    3. Try using a property decorator to validate property values.