I am currently converting a React project to TypeScript and using Packages like Next.js, next-i18next, and styled-components.
EDIT:
The information provided here may be outdated due to current versions of next-i18next
.
Please check out: Typescript i18next does not satisfy the constraint 'string | TemplateStringsArray NextJS
For a quick example, consider the following code snippet:
{t<string, ItemProps[]>('document.items', {returnObjects: true}).map(({ name, description, index }) => (
<li key={index}>
<strong dangerouslySetInnerHTML={{__html: name}} />
<Paragraph dangerouslySetInnerHTML={{__html: description}} />
</li>
)
)}
You can also view a working solution in this codesandbox.
Original Question:
In my language json file, I used an array of objects as shown below:
{
"websites":
[
{
"slug": "website-a",
"name": "Website A"
},
{
"slug": "website-b",
"name": "Website B"
}
]
}
To list all websites using i18next's { t }
:
t('websites', {returnObjects: true}).map(({slug, name}) => ( ... ))
When using TypeScript, it showed an error for map
:
Property 'map' does not exist on type 'string'.
To address this issue, I defined types and modified the code:
type websiteProps = {
map: Function;
};
type itemProps = {
slug: string;
name: string;
};
t<websiteProps>('websites', {returnObjects: true}).map(({slug, name}: itemProps) => ( ... ))
This solution resolved the issue but I am open to suggestions for better alternatives. Any feedback is appreciated!
Thank you!