Bir decorator, bir sınıfa, metoda, özelliğe veya parametreye davranış veya metadata ekleyen özel bir bildirimdir (@name). Runtime'ın decoratörlü hedefle çağırdığı bir fonksiyondur ve bunu bildirim olarak sarmalama veya açıklama yapmanızı sağlar.
// A simple method decorator that logs calls
function log(target: any, key: string, desc: PropertyDescriptor) {
const original = desc.value;
desc.value = function (...args: any[]) { // wrap the original method
console.log(`calling ${key} with`, args);
return original.apply(this, args);
};
}
class Service {
@log
fetch(id: number) { return { id }; }
}
new Service().fetch(1); // logs "calling fetch with [1]" then runs
Decorator, metod tanımlayıcısını aldı ve onu bir wrapper ile değiştirdi — metod gövdesine dokunmadan cross-cutting davranış (logging, caching, timing).
En çok gördüğünüz yer: frameworks
@Controller("users") // NestJS — declares a route controller
export class UsersController {
@Get(":id") // maps GET /users/:id
findOne(@Param("id") id: string) { return id; } // param decorator injects the route param
}
@Entity() // TypeORM — maps a class to a DB table
class User { @Column() name: string; }
NestJS, Angular, TypeORM ve class-validator, DI, routing, ORM eşlemesi ve doğrulama için decorators etrafında inşa edilmiştir.
İki çeşit (önemli)
{ "experimentalDecorators": true, "emitDecoratorMetadata": true }
Yukarıdaki legacy (experimental) decorators, Nest/Angular/TypeORM'un bugün güvendiği şeydir. Ayrıca daha yeni bir TC39 Stage-3 decorators (TS 5+) vardır ve bunlar farklı bir imzaya sahiptir, bunlar gelecekteki standarttır — ancak mevcut çoğu framework hala eski formu kullanmaktadır.
Neden önemli
Decorators, temiz, bildirim temelli meta-programming'i etkinleştirirler — sunucu frameworks ve ORM'lerin omurgası.
Hem mekanizmi (hedefi saran bir fonksiyon) hem de eski-vs-standart ayrımını bilmek, NestJS/Angular ekosisteminde çalışmak için gereklidir.
