Home > Mobile >  errors ts(7053) and ts(2538) in Next.js Ts
errors ts(7053) and ts(2538) in Next.js Ts

Time:01-24

i have googled and found kinda same issues but as i' new to TS i couldn't implement to my case. So

In my nextjs ts app, i enabled internalization for 4 languages. The content is static and comes from backend.


This is the shape of all of my static content

field: {
 en: "",
 ru: "",
 uz: "",
 oz: ""
}

and this is a simplified demonstration of how i'm showing them depending on the site language:

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)

i tried:

router.locale && static_content.title[router.locale]

but in this case it says:

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)


Data comes from backend looks like this:

{
 title_en: "",
 title_ru: "",
 title_uz: "",
 title_oz: "",
 ...
}

and this is how i'm displaying it

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)

error 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)

The project was already finished in javascript, i just wanted to convert to typescript. This is the only type error i couldn't solve because i'm new to ts and this only error exists in my 20 pages 2-4 per page so i would like to have simply solution.

Thank you in advance!

CodePudding user response:

Can we try and declare an interface for representing static content like so...

interface StaticContent {
  title: { [key: string]: string };
}

and then assign this type to the incoming data like so...


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

and then we can easily do

router.locale && static_content.title[router.locale]

Do we have any problem with this approach in your codebase?

  •  Tags:  
  • Related