类型“typeof Intl”上不存在属性“RelativeTimeFormat”

Won*_*rin 13 typescript

编写代码时没有错误,但是在编译时出现了这种情况:

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.
Run Code Online (Sandbox Code Playgroud)

虽然这个问题在这个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"
  ]
}
Run Code Online (Sandbox Code Playgroud)

打字稿版本:4.0.3

Hug*_*dby 7

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

您首先需要安装更新版本的 typescript:`npm install -D typescript@^4.1.2

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

"compilerOptions": {
  ...
  "lib": [
    "DOM",
    "ES2020",
    "ESNext"
    ],
  ...
}
Run Code Online (Sandbox Code Playgroud)

另一种解决方案是使用 polyfill 来代替。这将确保您的 React 应用程序可以在不支持 ES2020 标准的旧版浏览器中运行。请参阅此处https://formatjs.io/docs/polyfills/intl-relativetimeformat/