TS 5.x 신기능 총정리 — const 타입 매개변수부터 최신까지
TypeScript 5.x 시리즈는 성능 개선, 새로운 타입 기능, ECMAScript 제안 지원 등 메이저 업데이트 가 이어지고 있습니다.
TypeScript 5.0
TC39 Stage 3 데코레이터
// 표준 데코레이터 (experimentalDecorators 불필요)
function logged<T extends (...args: any[]) => any>(
target: T,
context: ClassMethodDecoratorContext
): T {
function replacement(this: any, ...args: any[]) {
console.log(`${String(context.name)} 호출`);
return target.call(this, ...args);
}
return replacement as T;
}
class Service {
@logged
getData() { return 'data'; }
}
const 타입 매개변수
// as const 없이도 리터럴 타입으로 추론
function routes<const T extends readonly string[]>(paths: T): T {
return paths;
}
const result = routes(['/home', '/about', '/contact']);
// readonly ['/home', '/about', '/contact'] — as const 없이도 리터럴!
모든 enum이 유니온 enum으로
// TS 5.0부터 모든 enum 멤버가 자신의 타입을 가짐
enum Color { Red, Green, Blue }
// Color.Red의 타입은 Color.Red (이전에는 그냥 Color)
TypeScript 5.1
명시적 undefined 반환 허용
// TS 5.1 이전에는 에러
function f(): undefined {
// return 문 없이도 OK
}
getter/setter 타입 분리
class Box {
#value: string = '';
// getter와 setter의 타입이 달라도 됨
get value(): string {
return this.#value;
}
set value(newValue: string | number) {
this.#value = String(newValue);
}
}
TypeScript 5.2
using 키워드 (Explicit Resource Management)
class Connection implements Disposable {
[Symbol.dispose]() {
console.log('연결 해제');
}
}
{
using conn = new Connection();
// 스코프 끝에서 자동 해제
}
TypeScript 5.3
import attributes
// JSON을 import할 때 어서트
import data from './data.json' with { type: 'json' };
switch(true) 좁히기
function processValue(value: string | number | boolean) {
switch (true) {
case typeof value === 'string':
value.toUpperCase(); // value: string
break;
case typeof value === 'number':
value.toFixed(); // value: number
break;
}
}
TypeScript 5.4
NoInfer 유틸리티 타입
// NoInfer로 특정 위치에서 타입 추론 방지
function createFSM<S extends string>(
initial: NoInfer<S>,
states: S[]
) {
return { current: initial, states };
}
// states에서 S를 추론하고, initial은 그 추론된 S에 맞는지 검증
createFSM('idle', ['idle', 'loading', 'done']); // OK
// createFSM('invalid', ['idle', 'loading', 'done']); // Error
클로저에서 좁혀진 타입 보존
function f(x: string | number) {
if (typeof x === 'string') {
// TS 5.4: 클로저 안에서도 x: string 유지 (특정 조건에서)
setTimeout(() => {
x.toUpperCase(); // 이전에는 에러, 5.4부터 OK (조건부)
});
}
}
TypeScript 5.5
isolatedDeclarations
{
"compilerOptions": {
"isolatedDeclarations": true
}
}
파일 단위 .d.ts 생성을 가능하게 해서 빌드 병렬화를 지원합니다.
타입 가드 자동 추론
// TS 5.5: filter에서 타입 가드를 자동 추론
const arr = [1, null, 2, undefined, 3];
const filtered = arr.filter((x) => x != null);
// TS 5.5: number[] (이전에는 (number | null | undefined)[])
이 기능은 정말 오래 기다린 것입니다. 더 이상 .filter((x): x is number => x != null) 같은 타입 가드를 명시할 필요가 없습니다.
정규식 검사
// 정규식 문법 오류를 컴파일 타임에 잡음
const regex = /(?<=\d+)\w+/; // ✅ OK
// const bad = /(?<=\d+/; // ❌ Error — 문법 오류
TypeScript 5.6
Disallowed Nullish and Truthy Checks
// 의미 없는 nullish 체크를 경고
const value = /regex/;
if (value) {
// ⚠️ 정규식은 항상 truthy — 의도한 검사인가?
}
Iterator Helper Types
// Iterator.prototype 메서드 지원
function* numbers() {
yield 1;
yield 2;
yield 3;
}
const doubled = numbers()
.map((n) => n * 2)
.filter((n) => n > 2);
마이그레이션 팁
// 단계적 업그레이드 — 한 번에 마이너 버전씩
// 5.0 → 5.1 → 5.2 → ...
{
"compilerOptions": {
// 새 기능을 점진적으로 활성화
"isolatedDeclarations": true, // 5.5+
"verbatimModuleSyntax": true // 5.0+
}
}
정리
| 버전 | 주요 기능 |
|---|---|
| 5.0 | 표준 데코레이터, const 타입 매개변수 |
| 5.1 | getter/setter 타입 분리 |
| 5.2 | using 키워드, Disposable |
| 5.3 | import attributes, switch(true) 좁히기 |
| 5.4 | NoInfer, 클로저 타입 보존 |
| 5.5 | isolatedDeclarations, 타입 가드 자동 추론 |
| 5.6 | nullish 체크 경고, Iterator Helpers |
- 새 프로젝트에서는 항상 최신 안정 버전을 사용하자
const타입 매개변수와 NoInfer는 라이브러리 개발에 특히 유용하다- TS 5.5의 타입 가드 자동 추론은 일상적인 코드 품질을 크게 개선한다
댓글 로딩 중...