属性"相对时间格式"在类型"typeof Intl"上不存在



编写代码时没有错误,但在编译过程中会发生这种情况:

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"
]
}

TypeScript版本:4.0.3

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

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

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

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

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

尝试设置Format.JS提供的Intl.RelativeTimeFormat polyfill

用法

通过polyfill.io

您可以使用polyfill.io URL生成器为Intl.RelativeTimeFormat创建polyfill脚本标记。默认情况下,创建的URL不附带任何区域设置数据。若要添加区域设置数据,请将Intl.RelativeTimeFormat.~locale.附加到功能列表中。例如:

<!-- Polyfill Intl.RelativeTimeFormat, its dependencies & `en` locale data -->
<script src="https://polyfill.io/v3/polyfill.min.js?features=Intl.RelativeTimeFormat,Intl.RelativeTimeFormat.~locale.en"></script>

简单

import '@formatjs/intl-relativetimeformat/polyfill'
import '@formatjs/intl-relativetimeformat/locale-data/en' // locale-data for en

动态导入+能力检测

import {shouldPolyfill} from '@formatjs/intl-relativetimeformat/should-polyfill'
async function polyfill(locale: string) {
const unsupportedLocale = shouldPolyfill(locale)
// This locale is supported
if (!unsupportedLocale) {
return
}
// Load the polyfill 1st BEFORE loading data
await import('@formatjs/intl-relativetimeformat/polyfill-force')
await import(
`@formatjs/intl-relativetimeformat/locale- 
data/${unsupportedLocale}`
)
}

最新更新