
프론트엔드
TypeScript DecoratorsTypeScript 데코레이터
TypeScript 데코레이터(Decorators)는 클래스, 메서드, 속성, 매개변수에 메타데이터나 기능을 선언적으로 추가하는 기능이다. @ 기호를 사용하며 NestJS, Angular, TypeORM 등 주요 프레임워크의 핵심이다.
데코레이터 종류
typescript
// 클래스 데코레이터
@sealed
class MyClass { ... }
// 메서드 데코레이터
class Service {
@log
getData() { ... }
}
// 속성 데코레이터
class User {
@required
name: string;
}
// 매개변수 데코레이터
class Controller {
getUser(@Param('id') id: string) { ... }
}클래스 데코레이터 구현
typescript
// 컴포넌트 등록 데코레이터
function Component(config: { selector: string; template: string }) {
return function <T extends new (...args: any[]) => {}>(constructor: T) {
return class extends constructor {
selector = config.selector;
template = config.template;
};
};
}
@Component({
selector: 'app-hello',
template: '<h1>Hello World</h1>',
})
class HelloComponent {
title = '안녕하세요';
}메서드 데코레이터
typescript
// 로깅 데코레이터
function log(target: any, key: string, descriptor: PropertyDescriptor) {
const original = descriptor.value;
descriptor.value = function (...args: any[]) {
console.log(`호출: ${key}(${JSON.stringify(args)})`);
const result = original.apply(this, args);
console.log(`결과: ${JSON.stringify(result)}`);
return result;
};
return descriptor;
}
// 메모이제이션 데코레이터
function memoize(target: any, key: string, descriptor: PropertyDescriptor) {
const cache = new Map();
const original = descriptor.value;
descriptor.value = function (...args: any[]) {
const cacheKey = JSON.stringify(args);
if (cache.has(cacheKey)) return cache.get(cacheKey);
const result = original.apply(this, args);
cache.set(cacheKey, result);
return result;
};
}
class MathService {
@log
@memoize
fibonacci(n: number): number {
if (n <= 1) return n;
return this.fibonacci(n - 1) + this.fibonacci(n - 2);
}
}NestJS 스타일 데코레이터
typescript
// NestJS 컨트롤러 패턴
@Controller('/users')
class UserController {
constructor(private userService: UserService) {}
@Get(':id')
async getUser(@Param('id') id: string): Promise<User> {
return this.userService.findById(id);
}
@Post()
@UseGuards(AuthGuard)
async createUser(@Body() dto: CreateUserDto): Promise<User> {
return this.userService.create(dto);
}
}관련 개념
- •TypeScript 제네릭
- •Angular
- •NestJS