타입스크립트의 데코레이터
이 문서에서는 타입스크립트의 데코레이터에 대해 설명합니다.
YouTube Video
타입스크립트의 데코레이터
타입스크립트 데코레이터는 클래스, 메서드, 접근자, 프로퍼티 또는 매개변수에 추가적인 기능이나 동작을 추가하는 메커니즘입니다. 데코레이터는 코드의 가독성과 재사용성을 향상시키는 강력한 도구입니다.
데코레이터의 기본
데코레이터는 클래스 또는 클래스 멤버에 추가 기능을 주입하는 함수입니다. 데코레이터는 타입스크립트 1.5에서 도입되었으며 ECMAScript 표준으로도 제안되었습니다.
1{
2 "compilerOptions": {
3 "experimentalDecorators": true
4 }
5}
- 데코레이터를 사용하려면
tsconfig.json
파일에서experimentalDecorators
옵션을 활성화해야 합니다.
데코레이터의 종류
타입스크립트에서는 다음 다섯 가지 데코레이터를 사용할 수 있습니다.
- 클래스 데코레이터 클래스에 적용되는 데코레이터.
- 메서드 데코레이터 클래스의 메서드에 적용되는 데코레이터.
- 접근자 데코레이터 클래스 속성의 getter나 setter에 적용되는 데코레이터.
- 속성 데코레이터 클래스의 속성에 적용되는 데코레이터.
- 매개변수 데코레이터 메서드의 매개변수에 적용되는 데코레이터.
클래스 데코레이터
클래스 데코레이터는 클래스에 적용되는 데코레이터입니다. 클래스 데코레이터는 클래스 정의 바로 위에 작성되며, 클래스 생성자에 접근할 수 있습니다. 주로 클래스의 동작을 변경하거나 메타데이터를 추가하는 데 사용됩니다.
1function Logger(constructor: Function) {
2 console.log(`Class ${constructor.name} is being constructed`);
3}
4
5@Logger
6class Person {
7 constructor(public name: string) {}
8}
9
10const person = new Person('John');
11// Output: Class Person is being constructed
이 예제에서는 Logger
데코레이터가 클래스에 적용되며, 클래스가 초기화될 때 콘솔에 메시지가 출력됩니다.
메서드 데코레이터
메서드 데코레이터는 클래스 메서드에 적용되며, 메서드 호출과 동작을 변경할 수 있습니다. 메서드 데코레이터는 세 개의 인수를 받습니다.
- 클래스의 프로토타입
- 메서드의 이름
- 메서드의 프로퍼티 디스크립터
1function LogExecutionTime(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
2 const originalMethod = descriptor.value;
3
4 descriptor.value = function (...args: any[]) {
5 console.time(propertyKey);
6 const result = originalMethod.apply(this, args);
7 console.timeEnd(propertyKey);
8 return result;
9 };
10}
11
12class MathOperations {
13 @LogExecutionTime
14 add(a: number, b: number): number {
15 return a + b;
16 }
17}
18
19const math = new MathOperations();
20math.add(2, 3);
21// Output: add: 0.000ms (execution time is displayed)
이 예제에서 LogExecutionTime
데코레이터가 메서드에 적용되며, 메서드의 실행 시간이 기록됩니다.
접근자 데코레이터
접근자 데코레이터는 클래스 프로퍼티의 getter
또는 setter
에 적용됩니다. 프로퍼티 값이 변경될 때 동작을 추가하는 데 유용합니다.
1function LogAccess(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
2 const originalGet = descriptor.get;
3 const originalSet = descriptor.set;
4
5 if (originalGet) {
6 descriptor.get = function () {
7 console.log(`Getter called for ${propertyKey}`);
8 return originalGet.call(this);
9 };
10 }
11
12 if (originalSet) {
13 descriptor.set = function (value: any) {
14 console.log(`Setter called for ${propertyKey} with value: ${value}`);
15 originalSet.call(this, value);
16 };
17 }
18}
19
20class Car {
21 private _speed: number = 0;
22
23 @LogAccess
24 get speed() {
25 return this._speed;
26 }
27
28 set speed(value: number) {
29 this._speed = value;
30 }
31}
32
33const car = new Car();
34car.speed = 120; // Setter called for speed with value: 120
35console.log(car.speed); // Getter called for speed → 120
이 예제에서는 접근자 데코레이터를 사용하여 getter
와 setter
가 호출될 때 출력을 기록합니다.
프로퍼티 데코레이터
프로퍼티 데코레이터는 클래스 프로퍼티에 적용되지만, 프로퍼티의 값이나 동작을 직접 변경할 수는 없습니다. 프로퍼티의 메타데이터를 가져오는 데 사용됩니다.
1function Readonly(target: any, propertyKey: string) {
2 Object.defineProperty(target, propertyKey, {
3 writable: false
4 });
5}
6
7class Book {
8 @Readonly
9 title: string = "TypeScript Guide";
10}
11
12const book = new Book();
13book.title = "New Title"; // Error: Cannot assign to read only property 'title'
이 예제에서 Readonly
데코레이터는 title
프로퍼티에 적용되며, 해당 프로퍼티는 읽기 전용으로 설정됩니다.
파라미터 데코레이터
파라미터 데코레이터는 메서드의 매개변수에 적용됩니다. 주로 메타데이터를 저장하거나 매개변수를 검증하는 데 사용됩니다. 데코레이터는 세 개의 인수를 받습니다.
- 클래스의 프로토타입
- 메서드의 이름
- 파라미터 인덱스
1function LogParameter(target: any, propertyKey: string, parameterIndex: number) {
2 console.log(`Parameter at index ${parameterIndex} in method ${propertyKey} was decorated.`);
3}
4
5class User {
6 greet(@LogParameter message: string) {
7 console.log(message);
8 }
9}
10
11const user = new User();
12user.greet('Hello!');
13// Output: Parameter at index 0 in method greet was decorated.
이 예제에서 LogParameter
데코레이터가 greet
메서드의 첫 번째 매개변수에 적용되며, 메서드가 호출될 때 해당 매개변수가 데코레이트되었다는 로그를 남깁니다.
데코레이터의 실용적 예제
데코레이터는 Angular와 같은 프레임워크에서 널리 사용되며, 특히 의존성 주입과 메타데이터 정의에 사용됩니다. 예를 들어, Angular 컴포넌트를 정의하기 위해 아래와 같이 @Component
데코레이터를 사용할 수 있습니다.
1@Component({
2 selector: 'app-root',
3 template: '<h1>Hello World</h1>',
4})
5export class AppComponent {}
따라서 데코레이터는 종종 프레임워크와 라이브러리의 핵심 부분으로 사용되며, 코드를 간결하고 명료하게 만듭니다.
데코레이터 요약
TypeScript 데코레이터는 클래스, 메서드 및 프로퍼티에 기능을 유연하게 추가하는 강력한 도구입니다. 사용자 지정 데코레이터를 사용하면 코드의 유지보수성과 재사용성을 향상시키고 추가적인 추상화를 가능하게 합니다. 데코레이터는 Angular와 NestJS 같은 프레임워크에서 중요한 역할을 하며, 이를 이해하면 이러한 프레임워크가 어떻게 작동하는지 깊이 이해할 수 있습니다.
위의 기사를 보면서 Visual Studio Code를 사용해 우리 유튜브 채널에서 함께 따라할 수 있습니다. 유튜브 채널도 확인해 주세요.