我搜索并发现了一些类似的问题,但由于我刚加入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完成了,我只想转换成类型记录。这是唯一的类型错误,我无法解决,因为我是新的ts和这个唯一的错误存在于我的20页2-4页,所以我想有一个简单的解决方案。
提前谢谢你!
发布于 2022-01-23 08:40:08
我们可以试着像这样声明一个表示static content的接口吗.
interface StaticContent {
title: { [key: string]: string };
}然后把这个类型分配给传入的数据,比如.
const static_content: StaticContent = {
title: {
en: "Main title",
ru: "Основное название",
uz: "Bosh sahifa",
oz: "Бош саҳифа"
}
// ...
}然后我们就可以很容易地
router.locale && static_content.title[router.locale]您的代码库中的这种方法有问题吗?
https://stackoverflow.com/questions/70820241
复制相似问题