【问题标题】:i18next: Map an array of objects in TypeScripti18next:在 TypeScript 中映射对象数组
【发布时间】:2022-05-06 15:37:33
【问题描述】:

我正在将一个 React 项目重写为 TypeScript。

包:Next.js、next-i18next、styled-components

编辑:

答案在当前next-i18next 版本中已过时。

请参考: Typescript i18next does not satisfy the constraint 'string | TemplateStringsArray NextJS

快速示例:

{t<string, ItemProps[]>('document.items', {returnObjects: true}).map(({ name, description, index }) => (
  <li key={index}>
    <strong dangerouslySetInnerHTML={{__html: name}} />
    <Paragraph dangerouslySetInnerHTML={{__html: description}} />
  </li>
   )
)}

我还为此解决方案创建了codesandbox

原问题:

我在语言 json 文件中使用了一组对象:

{
  "websites":
  [
    {
      "slug": "website-a",
      "name": "Website A"
    },
    {
      "slug": "website-b",
      "name": "Website B"
    }
  ]
}

用 i18next 的{ t } 列出所有这些:

t('websites', {returnObjects: true}).map(({slug, name}) => ( ... ))

TypeScript 下划线map:

Property 'map' does not exist on type 'string'.

用 TypeScript 重写了这个:

type websiteProps = {
  map: Function;
};

type itemProps = {
  slug: string;
  name: string;
};

t<websiteProps>('websites', {returnObjects: true}).map(({slug, name}: itemProps) => ( ... ))

这行得通,但我想知道我是否只是为.map“消除”下划线。 有什么更好的办法吗?

谢谢!

【问题讨论】:

    标签: typescript next.js react-i18next


    【解决方案1】:

    我对 i18 了解不多,但请尝试使用它:

    t<itemProps[]>('websites', {returnObjects: true}).map(({slug, name}: itemProps) => ( ... ))
    

    这告诉 TypeScript t 将返回一个 itemProps 数组。


    我想知道我是否只是为.map“删除”下划线

    您几乎不应该抑制 TypeScript 的编译器错误。但是,如果您确实需要,您可以在上面的行中使用// @ts-ignore

    【讨论】:

      【解决方案2】:

      @cherryblossom 的答案是正确的 - 我将发布作为新答案以帮助提供更多详细信息。

      这是基本 i18n t 函数的类型定义(由您的代码使用):

        <
          TResult extends TFunctionResult = string,
          TKeys extends TFunctionKeys = string,
          TInterpolationMap extends object = StringMap
        >(
          key: TKeys | TKeys[],
          options?: TOptions<TInterpolationMap> | string,
        ): TResult;
      

      它是一个通用函数,可以选择 TResult、Tkeys 和 TInterpolationMap。 我们可以看到,在没有任何类型参数的情况下调用时,TResult 默认为“字符串”。

      string 类型没有 .map 函数,因此会报错。

      由于您确定应该返回一组项目,因此您需要明确指定 TResult 类型参数,如 @cherryblossom 所示:

      t<itemProps[]>('websites', {returnObjects: true}).map(...)
      

      顺便说一句,您正在使用的库的类型定义在解决此类问题时非常有用。对于这种情况,请务必先检查。

      【讨论】:

        猜你喜欢
        • 2019-02-16
        • 2022-06-17
        • 1970-01-01
        • 2019-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-07
        • 1970-01-01
        相关资源
        最近更新 更多