You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 21使用Intl.DurationFormat遇TS2339错误的解决咨询

解决Angular v21中使用Intl.DurationFormat的编译错误

这个错误的核心原因是:TypeScript的默认类型定义库尚未包含Intl.DurationFormat的类型声明,即便目标浏览器已经原生支持该特性。以下是具体解决步骤:

1. 更新TypeScript库配置

在项目根目录的tsconfig.json中,修改compilerOptions下的lib数组,添加ES2023.Intl(确保加载包含该特性的最新Intl类型库):

{
  "compilerOptions": {
    "lib": ["ES2023", "DOM", "ES2023.Intl"]
    // 其他原有配置...
  }
}

2. 添加自定义类型声明(步骤1无效时使用)

如果更新lib配置后仍报错,可手动补全类型声明:

  1. 在src目录下新建typings文件夹,创建intl-duration-format.d.ts文件
  2. 写入以下内容:
declare namespace Intl {
  class DurationFormat {
    constructor(locale?: string | string[], options?: DurationFormatOptions);
    format(duration: Record<string, number>): string;
    formatToParts(duration: Record<string, number>): Array<{ type: string; value: string; unit?: string }>;
    static supportedLocalesOf(locale: string | string[], options?: unknown): string[];
  }

  interface DurationFormatOptions {
    style?: 'long' | 'short' | 'narrow';
    years?: 'numeric' | '2-digit';
    months?: 'numeric' | '2-digit';
    weeks?: 'numeric' | '2-digit';
    days?: 'numeric' | '2-digit';
    hours?: 'numeric' | '2-digit';
    minutes?: 'numeric' | '2-digit';
    seconds?: 'numeric' | '2-digit';
    milliseconds?: 'numeric' | '2-digit';
    fractionalDigits?: number;
    numberingSystem?: string;
  }
}

TypeScript会自动识别该声明文件,消除类型错误。

3. 验证浏览器兼容性配置

确认项目根目录的.browserslistrc或package.json中的browserslist配置包含原生支持Intl.DurationFormat的浏览器版本,例如:

last 2 Chrome versions
last 2 Firefox versions
last 2 Edge versions
last 2 Safari versions

Angular v21的默认配置通常已满足此要求,无需额外修改。

4. 兼容旧浏览器(可选)

如果需要支持尚未原生支持该特性的旧浏览器,可安装并引入polyfill:

  1. 安装依赖:
npm install @formatjs/intl-durationformat
  1. 在src/polyfills.ts中添加:
import '@formatjs/intl-durationformat/polyfill';
// 按需导入需要的语言包,例如英文
import '@formatjs/intl-durationformat/locale-data/en';

内容的提问来源于stack exchange,提问作者Steffen Harbich

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.02 03:47:31