我正在将 React 项目重写为 TypeScript。
软件包:Next.js、next-i18next、styled-components
EDIT:
截至目前,答案已过时next-i18next
版本。
请参阅:Typescript i18next 不满足约束 'string |模板字符串数组 NextJS https://stackoverflow.com/questions/69225989/typescript-i18next-does-not-satisfy-the-constraint-string-templatestringsarra
简单示例:
{t<string, ItemProps[]>('document.items', {returnObjects: true}).map(({ name, description, index }) => (
<li key={index}>
<strong dangerouslySetInnerHTML={{__html: name}} />
<Paragraph dangerouslySetInnerHTML={{__html: description}} />
</li>
)
)}
我还做了一个代码沙箱 https://codesandbox.io/s/react-i18next-typescript-array-example-5xdzk?file=/pages/index.tsx对于这个解决方案。
原问题:
我在语言 json 文件中使用了对象数组:
{
"websites":
[
{
"slug": "website-a",
"name": "Website A"
},
{
"slug": "website-b",
"name": "Website B"
}
]
}
用 i18next 列出所有这些{ t }
:
t('websites', {returnObjects: true}).map(({slug, name}) => ( ... ))
带下划线的 TypeScriptmap
:
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
。
我还能做些什么更好的事情吗?
谢谢你!