TypeScript 5.0 베타 - Decorator 정식 지원

배경

회사 프로젝트에서 NestJS를 사용하면서 계속 experimentalDecorators: true 설정을 켜두고 있었다. TypeScript 5.0 베타가 공개되면서 드디어 ECMAScript Stage 3 Decorator가 정식 지원된다는 소식을 접했다.

주요 변경 사항

기존 experimental decorator와 새로운 표준 decorator는 문법이 약간 다르다.

// 기존 experimental decorator
function Logger(target: any, propertyKey: string) {
  console.log(`${propertyKey} called`);
}

// 새로운 표준 decorator (TS 5.0)
function logger(target: Function, context: ClassMethodDecoratorContext) {
  const methodName = String(context.name);
  return function(this: any, ...args: any[]) {
    console.log(`${methodName} called`);
    return target.apply(this, args);
  };
}

새 decorator는 context 객체를 통해 더 많은 메타데이터에 접근할 수 있다. kind, name, access, metadata 등의 정보를 제공한다.

성능 개선

TS 5.0에서는 컴파일러 자체도 많이 개선됐다. 내부적으로 namespace 대신 module로 재작성해서 빌드 속도가 10% 정도 빨라졌다고 한다.

실제로 프로젝트에 적용해보니 cold start 시간이 눈에 띄게 줄었다.

마이그레이션 계획

당장 프로덕션에 적용하기는 어렵다. NestJS가 새로운 decorator 스펙을 지원할 때까지 기다려야 할 것 같다. 하지만 새 프로젝트에서는 시도해볼 만하다.

tsconfig.json에서 experimentalDecorators를 제거하고 target을 ES2022 이상으로 설정하면 된다.