我正在将 nodejs 应用程序重写为 typescript,但我遇到了一个我无法解决的问题。我收到一条神秘消息:“元素隐式具有‘任意’类型,因为类型‘字符串’的表达式不能用于索引类型”(7053)。
这是我的代码示例:
function translationFunction(type: string, section: string, language: string) {
let translations = {
type1: {
section1: {
en: 'I mean this',
es: 'quiero decir esto'
},
section2: {
en: 'I do not understand',
es: 'no entiendo'
},
},
type2: {
section1: {
en: 'I mean this',
es: 'quiero decir esto'
},
section2: {
en: 'I do not understand',
es: 'no entiendo'
},
}
}
//return console.log(translations.type1.section2.en); - this works
return translations[type][section][language] // this does not work in typescript but works in javascript
}
translationFunction('type1', 'section2', 'es');
我正在寻找一个解决方案,我知道这需要用一个接口来处理吗?
interface translationsInterface {
[key: string]: any,
}
let translations: translationsInterface = {};
我已经尝试过可以解决此问题的方法,但对我不起作用。我仍然遇到错误。
回答1
translations:type
type lang = 'en' | 'es'
interface translationsInterface {
[type: string]: {
[section: string]: {
[key in lang]: string;
}
}
}
function translationFunction(type: string, section: string, language: lang) {
let translations: translationsInterface = {
type1: {
section1: {
en: 'I mean this',
es: 'quiero decir esto'
},
section2: {
en: 'I do not understand',
es: 'no entiendo'
},
},
}
return translations[type][section][language]
}
https://codesandbox.io/s/clever-river-gquv40?file=/src/index.ts