首页 > 解决方案 > i18next:在 TypeScript 中映射对象数组

问题描述

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

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

我在语言 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. 有什么更好的我可以做的吗?

谢谢!

标签: typescriptnext.jsreact-i18next

解决方案


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

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

这告诉 TypeScriptt将返回一个itemProps.


我想知道我是否只是为.map

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


推荐阅读