从JS转到TS会遇到一些问题,记录一下遇到的问题以及解决方法。
场景:需要一个以String类型作为索引的对象,作为对照获取相应的值。
// 接口数据
const objData = ['风','岩','雷','草','水','火','冰']
// 定义对象
const objList = {}
objData.forEach((key, index) => {
objList[key] = index+1
})
console.log(objList)
//{ '风': 1, '岩': 2, '雷': 3, '草': 4, '水': 5, '火': 6, '冰': 7 }
JS这样写没有问题,在TS的话VsCode就报错了ts(7053)objList[key]
元素隐式具有 "any" 类型,因为类型为 "string" 的表达式不能用于索引类型 "{}"。
在类型 "{}" 上找不到具有类型为 "string" 的参数的索引签名。ts(7053)
解决方案:
1.给对象增加类型
// 改动1
type strList = {
[key:string]: number
}
// 接口数据
const objData = ['风','岩','雷','草','水','火','冰']
// 定义对象
// 改动2
const objList:strList = {}
objData.forEach((key, index) => {
objList[key] = index+1
})
console.log(objList)
//{ '风': 1, '岩': 2, '雷': 3, '草': 4, '水': 5, '火': 6, '冰': 7 }
2.修改tsconfig.json(不建议)
增加配置项suppressImplicitAnyIndexErrors和ignoreDeprecations
{
"compilerOptions": {
...,
"ignoreDeprecations": "5.0", // 若项目使用的TS版本超过5.0,则需要加此配置项才起效
"suppressImplicitAnyIndexErrors": true,
...,
}
}
但是,一般来说objData的内容来源数据接口,objList[key]有可能会出现以下问题,
类型“null”不能作为索引类型使用。ts(2538)
因为返回的数据有可能为null,这时候需要改成
objList[key as string] = index+1