网站搜索

typescript - TS2339:类型 'typeof Intl' 上不存在属性 'DisplayNames'


我如何修复这种类型错误?TS2339:类型 'typeof Intl' 上不存在属性 'DisplayNames'。

我的函数:

export const getLanguageName = (locale: string | null) => {
  const localeName = new Intl.DisplayNames([locale], { type: 'language' });
  return localeName.of(locale);
};

答案#1

如果你来到这里是为了寻找 Angular 解决方案,我认为可以直接使用 target: "es2020",并在 tsconfig.base.ts(根目录下)中更新你的库声明

{
    "compilerOptions": {
            ...
            "target": "es2020",
            "lib": ["dom", "es2020"]
    }
}

这应该可以让你访问新的 Intl API 类型定义,从而消除编辑器的错误以及任何可能的编译错误。几年前,由于 async/await 和 zone.js 的一些问题,我们只能使用 es2015,但这个问题在 2021 年得到了处理。

答案#2

目前在 TypeScript 中仍然缺失

你可以使用声明合并来使类型在你的代码库中可用,或者你可以提交一个 TypeScript PR


此外,请确保目标浏览器支持此功能:https://caniuse.com/mdn-javascript_builtins_intl_displaynames_of

或者你可能需要一个填充库:

  • 如果你想把它包含在你的包中:https://formatjs.io/docs/polyfills/intl-displaynames/
  • 如果你想直接从 UA-sniffer CDN 加载它: https://polyfill.io/v3/polyfill.min.js?features=Intl.DisplayNames(参见构建器)

相关文章