PAYATHON 2026

Angular 21 使用 Intl.DurationFormat 时如何解决 TS2339 错误?

数据小许

结论

这个错误是因为 TypeScript 缺少 Intl.DurationFormat 的类型声明。如果保留 Angular 21,可以补充一份 .d.ts 声明;要兼容不支持该 API 的运行环境,还需要配合 polyfill。

Angular 21.0.x、21.1.x 和 21.2.x 要求的 TypeScript 版本范围是 >=5.9.0 <6.0.0,而 Intl.DurationFormat 的内置声明直到 TypeScript 6.0 才加入。在这个版本组合下,仅修改 target 无法解决问题。参见 Angular 版本兼容表和 TypeScript 添加声明的 PR。

为什么 browserslist 和 target 没有解决问题?

browserslist 描述应用面向的浏览器范围,不会为 TypeScript 添加 API 类型声明。浏览器是否实现某个 API,与编译器是否认识该 API 是两回事。

target 控制 JavaScript 语法的降级,也会影响默认加载的 lib。如果显式设置了 lib,还需要检查该配置。esnext 使用当前安装的 TypeScript 提供的声明,无法获取更新版本中的类型。TypeScript 5.9 的 esnext.intl.d.ts 中没有 DurationFormat,因此添加 ESNext.Intl 也无法补齐它。参见 target 配置说明和 TypeScript 5.9 的声明文件。

保留 Angular 21:补充类型声明

先确认项目实际使用的版本:

npm ls @angular/core @angular/compiler-cli typescript

如果目标运行环境已经支持原生 Intl.DurationFormat,可以新增 src/types/intl-duration-format.d.ts:

declare namespace Intl {
  type AppDurationInput = Partial<Record<
    | 'years'
    | 'months'
    | 'weeks'
    | 'days'
    | 'hours'
    | 'minutes'
    | 'seconds'
    | 'milliseconds'
    | 'microseconds'
    | 'nanoseconds',
    number
  >>;

  class DurationFormat {
    constructor(
      locales?: string | string[],
      options?: {
        style?: 'long' | 'short' | 'narrow' | 'digital';
      }
    );

    format(duration: AppDurationInput): string;
  }
}

这份最小声明覆盖了当前的构造方式和 format() 调用,没有列出完整 API。如果需要其他选项、formatToParts() 或 resolvedOptions(),应补充对应签名。

该文件用于扩展全局 Intl,不要在其中添加顶层 import 或 export。还要确保应用构建使用的 tsconfig.app.json 包含这个文件。如果现有 include 能匹配该文件,就无需修改;否则可以将路径追加到现有 files 数组,保留原有条目。

随后可以继续使用原生 API:

const formatter = new Intl.DurationFormat('en', { style: 'narrow' });

const result = formatter.format({
  hours: 1,
  minutes: 30,
});

重新执行 npm run start。如果仍出现相同的 TS2339,先检查声明文件是否被实际构建配置纳入。

需要兼容其他运行环境时怎么办?

类型声明不会提供运行时实现。MDN 的 Baseline 2025 表示,该功能从 2025 年 3 月起在当时最新的主要浏览器中可用,旧浏览器仍可能不支持。补充声明后,可以检测运行环境是否支持该 API;如果使用 SSR,也需要检查服务端运行环境。参见 MDN 兼容性说明。

const supported = typeof Intl.DurationFormat === 'function';

如果需要 polyfill,可以安装 FormatJS 实现,直接使用它导出的类:

npm install @formatjs/intl-durationformat
import { DurationFormat } from '@formatjs/intl-durationformat';

const formatter = new DurationFormat('en', { style: 'narrow' });
const result = formatter.format({ hours: 1, minutes: 30 });

这种写法使用包提供的实现和类型,无需前面的全局声明。运行环境需要支持 Intl.ListFormat 和 Intl.NumberFormat,或为这些依赖提供 polyfill。FormatJS 还指出,仅导入全局 polyfill 不会补充 TypeScript 类型声明。参见 FormatJS 使用说明。

升级时需要注意什么?

如果希望使用内置类型声明,需要将 Angular 和 TypeScript 一起升级到兼容的版本组合。Angular 21 的支持范围不包含 TypeScript 6.0,因此不要只在 Angular 21 项目中强行升级 TypeScript。升级后的具体版本要求应以 Angular 版本兼容表为准。

升级到包含该声明的 TypeScript 后,还要确保有效的 lib 配置加载对应声明,并移除临时添加的 DurationFormat 声明,避免重复定义。

备注:内容仅供参考。