상식닷컴
로그인
가입하기
2026년 상식닷컴 선정 식당 & 카페 리스트
2025년 2026년 신상 호텔 리스트
최근에 오픈한 호텔을 찾는다면 살펴보세요
일주일 식단표 어플
자동 일주일 식단표 어플
안드로이드
아이폰
주식 & 코인 차트의 신
1000만원으로 2000만원 만들기 프로젝트
수정하기 - 타입스크립트에서 Decorator란 무엇인가요?
닉네임
비밀번호
제목
내용
[이미지 업로드는 권한이 있는 사람만 가능. 하단 카톡으로 연락]
타입스크립트에서 Decorator는 클래스, 메서드, 접근자, 프로퍼티 또는 매개변수에 추가적인 기능을 부여할 수 있는 특별한 종류의 선언적 기능입니다. Decorator는 주로 코드의 재사용성을 높이고, 코드의 가독성을 향상시키며, 특정 기능을 쉽게 적용할 수 있도록 도와줍니다. 타입스크립트는 ECMAScript의 제안된 Decorator 기능을 지원하며, 이 기능은 주로 Angular와 같은 프레임워크에서 많이 사용됩니다. Decorator의 종류 타입스크립트에서 사용할 수 있는 Decorator의 종류는 다음과 같습니다: 1. 클래스 Decorator : 클래스 선언 위에 적용되며, 클래스의 생성자에 대한 정보를 수정하거나, 클래스의 인스턴스를 생성할 때의 동작을 변경할 수 있습니다. ```typescript function LogClass(target: Function) { console.log(`Class ${target.name} is created.`); } @LogClass class User { constructor(public name: string) {} } ``` 2. 메서드 Decorator : 클래스의 메서드 위에 적용되며, 메서드의 동작을 수정하거나, 메서드 호출 시 추가적인 로직을 실행할 수 있습니다. ```typescript function LogMethod(target: any, propertyKey: string, descriptor: PropertyDescriptor) { const originalMethod = descriptor.value; descriptor.value = function(...args: any[]) { console.log(`Method ${propertyKey} is called with args: ${JSON.stringify(args)}`); return originalMethod.apply(this, args); }; } class User { @LogMethod sayHello(name: string) { return `Hello, ${name}!`; } } ``` 3. 접근자 Decorator : 클래스의 접근자(예: getter, setter) 위에 적용되며, 접근자의 동작을 수정할 수 있습니다. ```typescript function LogAccessor(target: any, propertyKey: string, descriptor: PropertyDescriptor) { const originalGet = descriptor.get; descriptor.get = function() { console.log(`Getting value of ${propertyKey}`); return originalGet.call(this); }; } class User { private _name: string; constructor(name: string) { this._name = name; } @LogAccessor get name() { return this._name; } } ``` 4. 프로퍼티 Decorator : 클래스의 프로퍼티 위에 적용되며, 프로퍼티의 메타데이터를 추가하거나, 프로퍼티의 동작을 변경할 수 있습니다. ```typescript function LogProperty(target: any, propertyKey: string) { let value: any; const getter = () => { console.log(`Getting value of ${propertyKey}`); return value; }; const setter = (newValue: any) => { console.log(`Setting value of ${propertyKey} to ${newValue}`); value = newValue; }; Object.defineProperty(target, propertyKey, { get: getter, set: setter, enumerable: true, configurable: true, }); } class User { @LogProperty name: string; constructor(name: string) { this.name = name; } } ``` 5. 매개변수 Decorator : 메서드의 매개변수에 적용되며, 매개변수에 대한 메타데이터를 추가할 수 있습니다. ```typescript function LogParameter(target: any, propertyKey: string, parameterIndex: number) { console.log(`Parameter at index ${parameterIndex} in method ${propertyKey} is decorated.`); } class User { greet(@LogParameter name: string) { return `Hello, ${name}!`; } } ``` Decorator의 사용 목적 1. 코드의 재사용성 : Decorator를 사용하면 공통적인 기능을 여러 클래스나 메서드에 쉽게 적용할 수 있습니다. 예를 들어, 로깅, 권한 검사, <a href='https://sangseek.com/sangseeks/캐싱/ko'>캐싱</a> 등의 기능을 Decorator로 구현하여 코드의 중복을 줄일 수 있습니다. 2. 가독성 향상 : Decorator를 사용하면 코드의 의도를 명확하게 표현할 수 있습니다. 예를 들어, 특정 메서드가 어떤 기능을 수행하는지 Decorator를 통해 쉽게 알 수 있습니다. 3. 메타프로그래밍 : Decorator는 메타데이터를 추가하는 데 유용합니다. 이를 통해 런타임에 클래스나 메서드에 대한 정보를 동적으로 처리할 수 있습니다. 결론 타입스크립트의 Decorator는 강력한 기능으로, 코드의 구조를 개선하고, 재사용성을 높이며, 가독성을 향상시키는 데 도움을 줍니다. 그러나 Decorator의 사용은 코드의 복잡성을 증가시킬 수 있으므로, 적절한 상황에서 신중하게 사용하는 것이 중요합니다. Decorator를 활용하여 더 나은 아키텍처와 유지보수성을 가진 코드를 작성할 수 있습니다.
이용안내
커뮤니티 이용안내
×
- 게시한 게시글로 발생하는 문제는 게시자에게 책임이 있습니다.
- 게시글이 타인/타업체의 저작권을 침해할 경우 모든 책임은 게시자에게 있습니다. 게시자가 모든 손해를 부담해야 합니다.
- 상식닷컴 운영자는 게시자와 상의하지 않고 게시글을 수정 또는 삭제할 수 있습니다.
- 상식닷컴 운영자는 깨끗한 커뮤니티 공간을 만드는 것이 1순위입니다.
수정하기
취소하기