我正在尝试输入要使用 i18next 进行翻译的对象数组,但变量 navItems 中出现以下消息,我在其中声明 i18next 然后迭代该数组
Type 'NavItemProps[]' does not satisfy the constraint 'string | TemplateStringsArray'. Property 'raw' is missing in type 'NavItemProps[]' but required in type 'TemplateStringsArray'
在地图内属性“map”
message does not exist on type 'string | object | (string | object)[]'. Property 'map' does not exist on type 'string'
我用它作为通过此链接输入 i18next 的参考,但没有成功i18next:在 TypeScript 中映射对象数组
组件
const DesktopNav = ({hasBackground}: DesktopNavProps) => {
const {t} = useTranslation('navbar')
const linkColor = useColorModeValue(
hasBackground ? 'black' : 'white',
'gray.200'
)
const linkHoverColor = useColorModeValue('gray.400', 'white')
const popoverContentBgColor = useColorModeValue('white', 'gray.800')
const navItems = t<NavItemProps[]>('menu', {returnObjects: true})
return (
<C.List display={'flex'} alignItems={'center'}>
{navItems?.map((item: NavItemProps, index: number) => (
<C.ListItem key={index}>
<C.Popover trigger={'hover'} placement={'bottom-start'}>
<C.PopoverTrigger>
<C.Link
p={3}
href={item.href ?? '#'}
fontWeight={500}
color={linkColor}
_hover={{
textDecoration: 'none',
color: linkHoverColor,
}}
>
{item.label}
</C.Link>
</C.PopoverTrigger>
</C.Popover>
</C.ListItem>
))}
</C.List>
)
}
界面
interface NavItemProps {
label: string
href?: string
subLabel?: string
children?: Array<NavItemProps>
}
Json 文件翻译
{
"menu": [
{
"label": "jobs",
"href": "/"
},
{
"label": "about",
"href": "/about"
},
{
"label": "Blog",
"href": "/blog"
},
{
"label": "contact",
"href": "/contact"
}
]
}
我无法准确地说出这种情况发生的时间(在哪个版本中),但显然与您引用的链接相比,react-i18next 类型定义中
t
函数的泛型顺序已发生变化。当前的定义是:
<
TKeys extends TFuncKey<N> | TemplateStringsArray extends infer A ? A : never,
TDefaultResult extends TFunctionResult = string,
TInterpolationMap extends object = StringMap
>(
key: TKeys | TKeys[],
options?: TOptions<TInterpolationMap> | string,
): TFuncReturn<N, TKeys, TDefaultResult>;
如您所见,第一种类型指的是键,第二种类型指的是结果。所以我想你可以这样使用它:
const navItems = t<string, NavItemProps[]>('menu', { returnObjects: true });
从 i18next 版本 23 开始,您需要将 3 个类型参数传递给
t
函数。第一个是键的类型,第二个是您传递的选项,第三个是返回类型。
您需要写:
const navItems = t<string, { returnObjects: true }, NavItemProps[]>('menu', { returnObjects: true });
它非常冗长,您可能想创建自己的可重用函数来减少样板文件。