我已經用谷歌搜索并發現了同樣的問題,但作為我對 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 頁中,所以我想要簡單的解決方案。
先感謝您!
uj5u.com熱心網友回復:
我們可以嘗試宣告一個這樣的介面來表示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://www.uj5u.com/qita/419746.html
標籤:
上一篇:如何在反應打字稿中使用React.ChangeEventHandler<HTMLInputElement>獲取輸入值
