Typescript报错expression of type string cannot be used to index

在使用TypeScript时遇到了一个报错:'Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type ‘Object’. No index signature with a parameter of type ‘string’ was found on type ‘Object’. 这个错误表明尝试用字符串索引来访问一个没有明确字符串索引类型的对象。解决方案通常涉及为对象定义索引签名或确保使用已知的键来访问对象属性。可以参考StackOverflow上的相关问题进行解决。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

const someObj:ObjectType = data;
const field = 'username';

// This gives an error
const temp = someObj[field];

报错:

Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type ‘Object’.
No index signature with a parameter of type ‘string’ was found on type ‘Object’.

// Solution 1: When the type of the object is known
const temp = someObj[field as keyof ObjectType]

// Solution 2: When the type of the object is not known
const temp = someObj[field as keyof typeof someObj]

参考:https://stackoverflow.com/questions/57086672/element-implicitly-has-an-any-type-because-expression-of-type-string-cant-b

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值