【发布时间】:2022-01-23 16:40:08
【问题描述】:
我已经用谷歌搜索并发现了一些相同的问题,但是作为我对 TS 的新手,我无法在我的案例中实施。所以
在我的nextjs + ts 应用程序中,我启用了 4 种语言的内部化。
内容是静态的,来自后端。
这是我所有静态内容的形状
field: {
en: "",
ru: "",
uz: "",
oz: ""
}
这是我如何根据网站语言显示它们的简化演示:
const static_content = {
title:{
en: "Main title",
ru: "Основное название",
uz: "Bosh sahifa",
oz: "Бош саҳифа"
}
...
}
import {useRouter} from 'next/router'
const router = useRouter()
static_content.title[router.locale] // Type 'undefined' cannot be used as an index type. ts(2538)
我试过了:
router.locale && static_content.title[router.locale]
但在这种情况下它说:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ en: string; ru: string; uz: string; oz: string; }'.
No index signature with a parameter of type 'string' was found on type '{ en: string; ru: string; uz: string; oz: string; }'.ts(7053)
来自后端的数据如下所示:
{
title_en: "",
title_ru: "",
title_uz: "",
title_oz: "",
...
}
这就是我展示它的方式
interface dataType {
title_en: string
title_ru: string
title_uz: string
title_oz: string
}
const data: dataType = await fetchData()
data['title_'+router.locale] // error ts(7053)
错误 ts(7053):
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'dataType'.
No index signature with a parameter of type 'string' was found on type 'dataType'.ts(7053)
该项目已经在 javascript 中完成,我只是想转换为 typescript。这是我唯一无法解决的类型错误,因为我是 ts 新手,而且这个唯一错误存在于我的 20 页每页 2-4 页中,所以我想要简单的解决方案。
提前谢谢你!
【问题讨论】:
标签: javascript typescript next.js