Typescript 类型为'的表达式;字符串';can';不能用于索引类型
很抱歉提出了另一个此类问题,但即使有类似的问题,我也无法将他们的解决方案应用到我的具体案例中 有人能帮我处理这个打字错误吗Typescript 类型为'的表达式;字符串';can';不能用于索引类型,typescript,Typescript,很抱歉提出了另一个此类问题,但即使有类似的问题,我也无法将他们的解决方案应用到我的具体案例中 有人能帮我处理这个打字错误吗 Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Record<RouteName, TranslatableRoute>'. No index signature with a parameter of
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Record<RouteName, TranslatableRoute>'.
No index signature with a parameter of type 'string' was found on type 'Record<RouteName, TranslatableRoute>'.(7053)
元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引类型“Record”。
在“记录”类型上未找到具有“字符串”类型参数的索引签名。(7053)
我正在寻找正确的方法来解决它,而不是通过破坏类型安全性来解决问题。下面是一些我遇到问题的虚拟示例
type RouteName = 'home' | 'account'
interface TranslatableRoute {
cs: string;
en: string;
}
const translatableRoutes: Record<RouteName, TranslatableRoute> = {
home: {
cs: '/',
en: '/'
},
account: {
cs: '/ucet',
en: '/account'
}
}
const findRoute = '/ucet'
const findLang = 'cs'
for (const key in translatableRoutes) {
if (translatableRoutes[key][findLang] === findRoute) {
console.log(`Found route\'s name is "${key}"!`)
}
}
type RouteName='home'|'account'
接口可转换路由{
cs:字符串;
en:字符串;
}
常量可翻译路由:记录={
主页:{
政务司司长:‘/’,
嗯:'/'
},
账户:{
政务司司长:‘/ucet’,
en:“/帐户”
}
}
常数findulote='/ucet'
const findLang='cs'
for(可翻译路由中的常量键){
if(translateableRoutes[key][findLang]==findulote){
log(`Found route'的名称是“${key}”!`)
}
}
Typescript playways.这里的问题是,
key
被推断为string
,而不是keyof-typeof-translateableroutes
,这在本例中是正确的
有各种各样的原因不能总是安全地推断,但最终的结果是TypeScript无法自动为您提供正确的类型
此外,还可以在循环中键入注释,因此无法在内联中手动修复它
幸运的是,您可以单独提供类型注释。将for in循环替换为:
let键:可翻译路由类型的键;
for(输入可翻译路由){
if(translateableRoutes[key][findLang]==findulote){
log(`Found route'的名称是“${key}”!`)
}
}
这有点麻烦,但它提供了
键
正确的类型,并确保以后一切正常安全运行,无需进行类型转换。感谢您的精彩解释。现在我明白了。