在Angular 21应用中使用Intl.DurationFormat
我通过Angular CI生成了一个基于最新v21的 Angular应用。 当我在TypeScript代码中添加 const formatter = new Intl.DurationFormat('en', { style: 'narrow' });,并执行 “npm run start” 启动应用时,出现错误:```
Application bundle generation failed. [0.914 seconds] - 2026-05-21T06:04:49.787Z
X [ERROR] TS2339: Property 'DurationFormat' does not exist on type 'typeof Intl'. [plugin angular-compiler]
src/app/app.ts:14:31:
14 │ ...nst formatter = new Intl.DurationFormat('de', { style: 'narrow'...
```
据我所知,Angular应该已经使用一个browserslist配置来支持 Intl.DurationFormat,因为根据MDN,截止2025年 3月的基线就已经可用。
我需要怎么做,才能在不产生转译错误的情况下使用这个 Intl 功能?将tsconfig.json的 "target": "esnext" 设置没有起作用,错误仍然相同。
解决方案
Angular v21将 TypeScript固定在 >=5.9.0 <6.0.0 版本,但 Intl.DurationFormat 是TypeScript在版本 6.0.0 中引入的,因此目前没有不使用变通方法就能实现的办法。
你可以简单地将来自 es2025.intl.d.ts 的类型定义复制到你的项目中,这样就能工作。一旦Angular支持TypeScript >=6.0.0,你就可以把它移除。
如果你想要支持较旧的浏览器,反正需要一个polyfill,可以直接使用 @formatjs/intl-durationformat。