reactjs - Typescript i18next 不满足约束 'string | TemplateStringsArray NextJS
问题描述
我正在尝试键入要使用 i18next 翻译的对象数组,但以下消息出现在变量 navItems 中,我在其中声明 i18next 然后迭代数组Type 'NavItemProps[]' does not satisfy the constraint 'string | TemplateStringsArray'. Property 'raw' is missing in type 'NavItemProps[]' but required in type 'TemplateStringsArray'
并在地图内属性“地图”message does not exist on type 'string | object | (string | object)[]'. Property 'map' does not exist on type 'string'
我将它用作通过此链接键入 i18next 的参考,但没有成功i18next: Map a array of objects in 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"
}
]
}
解决方案
我不能说这到底是什么时候(在哪个版本中)发生的,但是t
与您引用的链接相比,react-i18next 类型定义中函数泛型的顺序显然发生了变化。目前的定义是:
<
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 });
推荐阅读
- ruby - 检索步骤定义文件中的标记字符串
- ios - 将 IPA 上传到 App Store 时出错
- java - JDK8 RMI 服务器在 JDK9 或 JDK10 中不工作 - ClassNotFoundException
- c# - 调用线程必须是 STA 线程,因为许多带有 livechart 的 UI 组件都需要它
- generics - 有没有办法用不同的生命周期来表达“相同”的泛型类型?
- javascript - 错误:错误的 Twitter 流式传输请求:401 使用 Twit
- java - 如何编写具有多个连接的 Spring Data JPA 规范?
- asp.net - 使用特定模型更新运行迁移
- sql - 获取 Google 图表错误“轴 #0 的数据列不能是字符串类型”
- ios - Xcode 10:找不到此可执行文件的有效配置文件