What is a decorator?
- TypeScript course
- Intermediate
- Lesson 44/89
- 4 min
Learn what class decorators are.
What is a decorator?
A decorator is a function that annotates and modifies a class, method, or property. A class decorator is written as @Name right above the class declaration and receives the constructor function. The returned value (if any) replaces the class.
@Logged
class Foo {
selam() { return "merhaba"; }
}A decorator is a higher-order function
A decorator is essentially a higher-order function. Writing @Logged class Foo {} is equivalent to passing the Foo class to the Logged function. The decorator receives the constructor and returns it as-is or modified.
// equivalent to @Logged class Foo {}:
const Foo = Logged(class Foo {
selam() { return "merhaba"; }
});Practice Write a class decorator
Write a class decorator Logged that takes a ctor parameter, prints "sınıf hazır" with console.log, and returns ctor. Define class Foo with a selam method returning "merhaba". Apply the decorator manually by calling Logged with Foo and assigning the result to a variable LoggedFoo. Call the selam method on a new instance of the resulting class and print the result with console.log.
Starter code
// Logged fonksiyonunu yaz: ctor parametresi alsın
// "sınıf hazır" yazdır, ctor'yu döndür
// Foo sınıfını tanımla, selam metodu "merhaba" döndürsün
// LoggedFoo değişkenini Foo sınıfını Logged ile işleyerek oluştur
// yeni örnek üzerinden selam metodunu çağır, sonucu yazdırSample solution
function Logged(ctor: any): any {
console.log("sınıf hazır");
return ctor;
}
class Foo {
selam(): string {
return "merhaba";
}
}
const LoggedFoo = Logged(Foo);
console.log(new LoggedFoo().selam());Expected output
sınıf hazır merhaba
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How many arguments does a class decorator take and what is it?
- The constructor function (1 argument) Correct answer
- An instance of the class (1 argument)
- A method descriptor object (1 argument)
- A property name (1 argument)
Explanation: A class decorator takes one argument: the class's constructor function. Instance, method descriptor, and property name are arguments of other decorator kinds.
2 Return the constructor
function Logged(ctor: any): any {
console.log("sınıf hazır");
return ____;
}
function Logged(ctor: any): any {
console.log("sınıf hazır");
return ctor;
}
Explanation: A class decorator must return the constructor it received. this inside a function is not the constructor; null loses the class; new ctor() returns an instance, not the constructor.
3 Class decorator parts
| Term | Meaning |
|---|---|
@Logged |
Decorator marker and name |
class Foo |
The decorated class |
function Logged(ctor) |
Decorator function definition |
return ctor |
Returning the constructor |