首页 > 解决方案 > “typeof Intl”类型上不存在属性“RelativeTimeFormat”

问题描述

编写代码时没有错误,但是在编译期间会发生这种情况:

src/index.ts:2:24 - error TS2339: Property 'RelativeTimeFormat' does not exist on type 'typeof Intl'.

2   const rtf = new Intl.RelativeTimeFormat("en", { style: "long" });
                         ~~~~~~~~~~~~~~~~~~


Found 1 error.

虽然这个问题应该在这个 PR之后得到解决。

我的tsconfig

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "CommonJS",
    "moduleResolution": "Node",
    "outDir": "lib",
    "lib": [
      "DOM",
      "ESNext"
    ],
    "strict": true,
    "declaration": true,
    "removeComments": true,
    "sourceMap": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "importHelpers": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "isolatedModules": true
  },
  "include": [
    "src"
  ]
}

打字稿版本:4.0.3

标签: typescript

解决方案


根据您链接的 PR,它仅使用 TypeScript v4.1.2 发布。此外,它是es2020.intlTypeScript 库定义的一部分。

你首先需要安装一个更高版本的打字稿:`npm install -D typescript@^4.1.2

然后,您必须使用以下内容更新您的 tsconfig:

"compilerOptions": {
  ...
  "lib": [
    "DOM",
    "ES2020",
    "ESNext"
    ],
  ...
}

另一种解决方案是使用 polyfill。这将确保您的 React 应用程序在不支持 ES2020 标准的旧浏览器中工作。见这里https://formatjs.io/docs/polyfills/intl-relativetimeformat/


推荐阅读