【问题标题】:errors ts(7053) and ts(2538) in Next.js + TsNext.js + Ts 中的错误 ts(7053) 和 ts(2538)
【发布时间】: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


【解决方案1】:

我们可以尝试声明一个接口来表示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]

我们对您的代码库中的这种方法有任何问题吗?

【讨论】:

  • 是的,这适用于static content,谢谢。但是我能为dynamic content 做什么,我的大部分内容都是动态的?是否可以这样做 title[router.locale!] 而不是 router.locale && title[router.locale] 因为它的代码更少?
  • 你可以阅读Index Signatures。对于访问动态数据非常有用,非常适合您的情况。
  • { [key: string]: string } 也是一个索引签名,其中键的类型是string,值也是string。对于复杂类型,可以相应指定值的类型。
  • 唯一的问题是索引签名不允许访问undefined 值。为了防止在运行时出现这种情况下的错误,最好先进行条件检查,然后尝试访问。 router.locale && 进行条件检查,防止运行时错误访问。
  • 答案对您来说是否足够好,或者如果您希望它针对某些特定条件进行调整,请告诉我。
猜你喜欢
  • 2020-08-14
  • 1970-01-01
  • 2022-08-06
  • 2020-02-22
  • 2022-07-23
  • 2021-06-26
  • 2018-06-11
  • 2021-02-20
  • 1970-01-01
相关资源
最近更新 更多