首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Next.js + Ts中的错误ts(7053)和ts(2538)

Next.js + Ts中的错误ts(7053)和ts(2538)
EN

Stack Overflow用户
提问于 2022-01-23 08:11:20
回答 1查看 241关注 0票数 0

我搜索并发现了一些类似的问题,但由于我刚加入TS,我无法实现我的案例。所以

在我的nextjs + ts应用程序中,我启用了4种语言的内部化。内容是静态的,来自后端。

--这是我所有静态内容的形状

代码语言:javascript
复制
field: {
 en: "",
 ru: "",
 uz: "",
 oz: ""
}

这是一个简单的演示,展示了如何根据站点语言向他们展示:

代码语言:javascript
复制
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)

我试过:

代码语言:javascript
复制
router.locale && static_content.title[router.locale]

但在这种情况下,它说:

代码语言:javascript
复制
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)

数据来自后端,如下所示:

代码语言:javascript
复制
{
 title_en: "",
 title_ru: "",
 title_uz: "",
 title_oz: "",
 ...
}

我就是这样展示它的

代码语言:javascript
复制
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):

代码语言:javascript
复制
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页,所以我想有一个简单的解决方案。

提前谢谢你!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-23 08:40:08

我们可以试着像这样声明一个表示static content的接口吗.

代码语言:javascript
复制
interface StaticContent {
  title: { [key: string]: string };
}

然后把这个类型分配给传入的数据,比如.

代码语言:javascript
复制
const static_content: StaticContent = {
  title: {
    en: "Main title",
    ru: "Основное название",
    uz: "Bosh sahifa",
    oz: "Бош саҳифа"
  }
  // ...
}

然后我们就可以很容易地

代码语言:javascript
复制
router.locale && static_content.title[router.locale]

您的代码库中的这种方法有问题吗?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70820241

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档