Featured image of post TypeScript 新功能快速概述Featured image of post TypeScript 新功能快速概述

TypeScript 新功能快速概述

對日常開發中有用的 TypeScript 新功能的簡要總結。

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 開始,第 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),推理範圍將擴大到 stringsatisfies 執行類型檢查而不會遺失文字推斷-這是一個明顯的勝利。

改進的模組解析度 (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 功能都朝著相同的方向發展:更強的類型安全性和更少的樣板程式碼。 satisfiesconst 類型參數特別容易引入現有程式碼庫並提供即時價值。確保在升級時利用這些新功能。