我正在尝试键入要使用 i18next 转换的对象数组,但以下消息出现在变量 navItems 中,我在其中声明 i18next 然后迭代数组 Type 'NavItemProps[]' 不会满足约束 'string |模板字符串数组'。 “NavItemProps[]”类型中缺少属性“raw”,但在“TemplateStringsArray”类型中是必需的
并且在 map 内部,属性“ map ”消息在类型“字符串”上不存在 |对象 | (字符串 | 对象)[]'。 “字符串”类型不存在属性“ map ”
我用它作为通过此链接键入 i18next 的引用,但没有成功 i18next: Map an 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 });
关于reactjs - Typescript i18next 不满足约束 'string |模板字符串数组 NextJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69225989/
相关文章:
java - 如何检查至少一个 boolean 值是否为真?
swift - 是否有可能在 Swift 的枚举中将多个案例分组并表示为另一个案例?
apache-kafka - 如何为 Kafka 主题实现生存时间 (TTL)
javascript - leetcode 如何做到这一点 : Read user's input
c - Valgrind : Invalid read of size 1
android - Jetpack Compose 中的副作用
php - 我必须在 Composer 要求之前使用 init 吗?
javascript - 如果 javascript 中的数据属性(HTML)=== 输入文本,如何