【TS】Error: Element implicitly has an ‘any‘ type because expression of type ‘string‘ can‘t be used to

4 篇文章 0 订阅

完整的报错是这样:

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

该报错一般出现在使用对象获取值的场景。

const obj = {
  name: '张三',
  age: 20,
};

const str = 'name' as string;

/**
  Error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ name: string; age: number; }'.
  No index signature with a parameter of type 'string' was found on type '{ name: string; age: number; }'.ts
 */
obj[str];

我们只需要确保str是obj的key就可以避免报错,常用的方式有以下几种:

方法一:

interface Person {
  name: string,
  age: number,
}
const obj: Person = {
  name: '张三',
  age: 20,
};

const str = 'name' as string;

console.log(obj[str as keyof typeof obj]);

方法二:

interface Person {
  name: string,
  age: number,
}
const obj: Person = {
  name: '张三',
  age: 20,
};

const str = 'name' as string;

console.log(obj[str as keyof Person]);

可以看到,这两种方式,极其相似,这里为什么不用typeof,是因为Person是我们定义的类型,而不是对象,两种方式得到的结果都是一样的。

// type T = 'name' | 'age'
type T = keyof Person;
type T = keyof typeof obj;

当然,如果str没有使用类型断言,这么写也是没有问题的,如下:

interface Person {
  name: string,
  age: number,
}
const obj: Person = {
  name: '张三',
  age: 20,
};

const str = 'name';

console.log(obj[str]);

好了,我们再考虑另一种场景,如果我obj对象里的属性很多,我很多地方都会用到obj对象里的key,总不能一个个都是keyof或者keyof typeof一下吧,有没有更好一点的方案呢?

方式三:

interface Person {
  name: string,
  age: number,
}
const obj: Person = {
  name: '张三',
  age: 20,
};

const str: keyof Person = 'name';

console.log(obj[str]);

如果我想给obj新增一个属性呢?直接加肯定会报错,如下:

interface Person {
  name: string,
  age: number,
}
const obj: Person = {
  name: '张三',
  age: 20,
};
// Error: Property 'sex' does not exist on type 'Person'.ts
obj.sex = 'boy';

在不确定key的值是否存在obj对象里时,可以使用下面这种方式:

interface Person {
  name: string,
  age: number,
  [key: string]: any,
}
const obj: Person = {
  name: '张三',
  age: 20,
};
obj.sex = 'boy';

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值