C.W.K.
Stream
Lesson 06 of 06 · published

TC39 Decorator: 새 (Stage 3) 맛

~11 min · classes, decorators, tc39, stage-3

Level 0Curious
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete
"Decorator 가 붙은 거 변환하는 함수. Stage 3 버전이 마침내 표준화."

Decorator 가 뭐 함

Decorator 가 class 정의 시점에 도는 함수, 붙은 거 수정 또는 대체 가능. @measure class Foo 가 class 에 `measure` decorator 적용. @log methodName(): void 가 method 에 적용. Decorator 함수가 target 에 대한 metadata 받고 대체 또는 `undefined` 반환.

Decorator 가 cross-cutting concern 에 유용: 로깅, timing, validation, caching, dependency injection, observability hook. 많은 class 멤버 가로질러 중복할 어떤 거든 decorator 로 들어 올림 가능.

Stage 3 vs experimentalDecorators 구별

TypeScript 가 `experimentalDecorators` tsconfig flag 하에 몇 년 동안 decorator 지원. 그게 변경 없이 표준화 통과 안 한 옛 TC39 proposal. TypeScript 5.0 이 표준화 Stage 3 형태 지원 추가 — flag 불필요, 문법/의미 다름.

대부분 modern 코드가 Stage 3 target 해야. experimentalDecorators 쓰는 legacy 코드 여전히 작동 (flag 유지), 근데 새 프로젝트는 그 flag 활성화 안 해야.

Stage 3 decorator 모양

Stage 3 decorator 가 decorate 하는 거 (class, method, accessor, field) 기반 특정 signature 가진 함수. Method decorator 엔: function myDecorator(target: Function, context: ClassMethodDecoratorContext) { ... }. Decorator 가 대체 함수 (새 method 됨) 또는 `undefined` (대체 없음) 반환 가능. `context` argument 가 이름, kind, 고급 패턴용 add/finishedHook 운반.

Decorator 가 learning curve 있는 power tool. 대부분 프로젝트엔 자기 거 쓰는 거보다 library-제공 decorator (NestJS, MobX, class-validator) 더 많이 써. 문법 알아보고, 기본 배우고, 진짜 cross-cutting 필요 있을 때 손 뻗어.

Code

Stage 3 decorator — method 와 class·typescript
// 단순 method decorator (Stage 3 문법).
function logged(originalMethod: any, context: ClassMethodDecoratorContext) {
  const methodName = String(context.name);
  return function (this: any, ...args: any[]) {
    console.log(`Calling ${methodName}(${args.join(', ')})`);
    const result = originalMethod.call(this, ...args);
    console.log(`${methodName} returned ${result}`);
    return result;
  };
}

class Calculator {
  @logged
  add(a: number, b: number): number {
    return a + b;
  }
}

const c = new Calculator();
c.add(2, 3);
// 출력:
//   Calling add(2, 3)
//   add returned 5

// Class decorator — class 를 wrapper 로 대체.
function sealed<T extends new (...args: any[]) => any>(
  Ctor: T,
  context: ClassDecoratorContext,
) {
  Object.seal(Ctor);
  Object.seal(Ctor.prototype);
  return Ctor;
}

@sealed
class Greeter {
  greet() { return 'hi' }
}

External links

Exercise

Method 가 실행하는데 얼마나 걸리는지 로깅하는 @timed decorator 써. 계산 하는 method 에 적용. Wrap 된 method 가 옳게 작동 AND timing 로깅 확인.
Hint
Decorator 가 performance.now() 전후 호출하는 wrapper 반환, originalMethod.call(this, ...args) 통해 원래 method 호출, 그다음 duration 로깅.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.