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 类型参数特别容易引入现有代码库并提供即时价值。确保在升级时利用这些新功能。