跳到主内容

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type

· 2分钟阅读

问题

写 ts 代码一时爽,一直报错一直爽,ts 作为一个强类型检测点框架。今天编写代码的时候要获取一个对象的值,报错了!!!

const allTypes = { jpg: true, gif: true, png: true, mp4: true };
const mediaType = url.substring(url.lastIndexOf(".") + 1).toLowerCase();
return Boolean(allTypes[mediaType]);

原因

主要原因还是 mediaType 的类型未知,ts 在类型检测的时候发现不了,所以报错了。

解决

有一个非常简单的解决办法,就是在遇到 expression of type string cannot be used to index 这类错误的时候,记住一下办法,百分之百可以解决。假设我们有以下数据

type ObjectType = {
name: string,
}

const someObj: ObjectType = {
name: '1024nav.com'
};

const field = "username";
// 下面直接获取就会报错
const temp = someObj[field];

这尼玛会报错,我返回一个 undefined 不就行了,可惜 ts 就是不给你过,我们可以这样写。

// 可以使用 keyof ObjectType
const temp1 = someObj[field as keyof ObjectType];
// 或者 keyof typeof someObj
const temp2 = someObj[field as keyof typeof someObj];