CodeBlanks Logo Icon CodeBlanks

Property decorator

Learn property decorators.

Property decorator

A property decorator is written right above a class property and takes two arguments: (target, key). target is the class prototype and key is the property name. Unlike a method decorator, no descriptor is provided; the property may not be initialized yet.

function Kayit(
  target: any,
  key: string
) {
  console.log("özellik: " + key);
}

class Kisi {
  @Kayit ad: string;
}

Property decorator use cases

Property decorators are typically used to register property names, add validation rules, or carry metadata. At runtime the property value may not be assigned yet; therefore the decorator usually records and processes the value later. For example, a system that auto-discovers form fields can collect field names via property decorators.

Practice Add property registration

Write the Kayit decorator taking (target: any, key: string) that prints the property name via console.log("özellik: " + key). Write class Kisi with property ad: string and constructor(ad: string) that does this.ad = ad. Apply the decorator manually by calling it with Kisi.prototype and "ad". Assign new Kisi("Ayşe") to a variable k, print k.ad with console.log.

Starter code

index.ts
// Kayit decorator'unu yaz: target ve key alır
// console.log ile "özellik: " + key yazdır
// Kisi sınıfı yaz: ad özelliği ve constructor(ad: string)
// constructor this.ad = ad yapsın
// Decorator'u Kisi.prototype ve "ad" ile çağırarak elle uygula
// k = new Kisi("Ayşe") ile örnek oluştur
// k.ad'ı yazdır

Sample solution

index.ts
function Kayit(target: any, key: string): void {
  console.log("özellik: " + key);
}

class Kisi {
  ad: string;
  constructor(ad: string) {
    this.ad = ad;
  }
}

Kayit(Kisi.prototype, "ad");
const k = new Kisi("Ayşe");
console.log(k.ad);

Expected output

özellik: ad
Ayşe

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How many arguments does a property decorator take?

  • 2 Correct answer
  • 3
  • 0
  • 1

Explanation: A property decorator takes two arguments: target (prototype) and key (property name). Three arguments belong to method decorators; one to class decorators.

2 Property decorator signature

Question
function Kayit(target: any, ____): void {
  console.log("özellik: " + key);
}
Answer
function Kayit(target: any, key: string): void {
  console.log("özellik: " + key);
}

Explanation: A property decorator takes two parameters: target and key. descriptor only appears in method decorators; value and ctor are not valid in this signature.

3 Property decorator parts

Term Meaning
target The class prototype
key The property name
(target, key) Property decorator signature
console.log(key) Printing the property name

All lessons in Intermediate