TypeScript 5.x 시리즈에는 유형 시스템을 강화하고 개발자 경험을 향상시키는 많은 기능이 도입되었습니다. 이 기사에서는 일상적인 코딩에 가장 유용한 것들을 강조합니다.
상수 유형 매개변수(5.0)
함수의 유형 매개변수에 const 수정자를 추가하면 값을 전달할 때 리터럴 유형이 유지됩니다.
function getConfig<T extends readonly string[]>(keys: T): T {
return keys
}
// Before: inferred as string[]
const config1 = getConfig(['dev', 'staging', 'prod'])
// With const type parameter: inferred as a tuple of literals
const config2 = getConfig<const>(['dev', 'staging', 'prod'])
// type: readonly ["dev", "staging", "prod"]
이는 객체 속성이 리터럴 유형을 유지하도록 하려는 경우 유용합니다. 호출 사이트에 as const을 작성할 필요가 없습니다. 코드는 깨끗하게 유지됩니다.
안정화된 데코레이터(5.0)
TypeScript 5.0부터 Stage 3 ECMAScript 데코레이터가 기본적으로 지원됩니다. 실험적 데코레이터와 달리 더 이상 컴파일러 옵션에서 experimentalDecorators을 활성화할 필요가 없습니다.
function log(target: any, context: ClassMethodDecoratorContext) {
const methodName = String(context.name)
return function (this: any, ...args: any[]) {
console.log(`${methodName} called with`, args)
return target.call(this, ...args)
}
}
class Calculator {
@log
add(a: number, b: number) {
return a + b
}
}
Angular 또는 NestJS에서 온 개발자는 구문이 익숙하다고 생각할 것이지만 변경 사항에 주목하십시오. 이제 공식 ECMAScript 사양을 따릅니다.
만족스러운 연산자(4.9 / 5.x)
satisfies을 사용하면 유추된 좁은 유형을 유지하면서 값이 유형을 준수하는지 확인할 수 있습니다.
type Color = 'red' | 'green' | 'blue'
type Palette = Record<string, Color>
const palette = {
primary: 'blue',
secondary: 'green',
// assigning 'yellow' here would trigger an error
} satisfies Palette
// palette.primary is inferred as "blue", not string
전통적인 유형 주석(: Palette)을 사용하면 추론이 string으로 확장됩니다. satisfies는 문자 그대로의 추론을 잃지 않고 유형 검사를 실행합니다. 이는 확실한 승리입니다.
향상된 모듈 해상도(5.x)
TypeScript 5.x에는 moduleResolution에 대한 bundler 옵션이 추가되었습니다. 이는 Vite 및 esbuild와 같은 최신 번들러가 모듈을 해결하는 방식과 일치합니다.
{
"compilerOptions": {
"moduleResolution": "bundler",
"module": "ESNext",
"target": "ES2022"
}
}
이를 통해 최신 생태계와의 호환성이 향상됩니다. package.json의 exports 필드가 올바르게 작동하고 .ts 확장자 없이 파일을 가져올 수 있습니다.
실용적인 템플릿 리터럴 유형
템플릿 리터럴 유형은 4.1에서 도입되었지만 이를 5.x의 공용체 유형과 결합하면 훨씬 더 강력해집니다.
type Size = 'sm' | 'md' | 'lg'
type Variant = 'primary' | 'secondary'
// "btn-sm-primary" | "btn-sm-secondary" | "btn-md-primary" ...
type ButtonClass = `btn-${Size}-${Variant}`
function getButtonClass(size: Size, variant: Variant): ButtonClass {
return `btn-${size}-${variant}`
}
이는 유형이 안전한 UI 구성 요소 클래스 이름이나 API 끝점 경로에 적합합니다.
마무리
모든 TypeScript 5.x 기능은 동일한 방향으로 이동합니다. 즉, 더 적은 상용구로 더 강력한 유형 안전성을 제공합니다. satisfies 및 const 유형 매개변수는 특히 기존 코드베이스에 쉽게 도입하고 즉각적인 가치를 제공할 수 있습니다. 업그레이드할 때 이러한 새로운 기능을 활용하십시오.

