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

当typescript编写代码时出现这个报错怎么办?

例如如下代码及声明

interface IJobData {
    generation?: {id: number; name: string; code: string;}[]
    publishing?: {id: number; name: string; code:string;}[]
}

const method = ['generation', 'publishing']
const originJobData = {
     generation: [
		{id: 1, name: 'generation',  code: 'test1'},
		{id: 2, name: 'test2', code: 'test2' }
 	 ],
 	 publishing: [
		{id: 3, name: 'publish', code: 'test3'},
		{id: 4, name: 'publish11', code: 'test4'},
	]
}

const formatJobData: IJobData = {}
method.forEach((method:string)=>{
 	if (originJobData[method])  formatJobData[method] = originJobData[method]
})

// 此时会报如下错误
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'IJobData'.
  No index signature with a parameter of type 'string' was found on type 'IJobData'

又比如:

const str = 'name' as string;

const obj = {
  name: 'James Doe',
  country: 'Chile',
};

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

当我们尝试通过对象的属性访问对象的value时,就会报这个错误;遇到这种问题我们如何解决呢?

第一个解决方案:
const str = 'name' as string;

const obj = {
  name: 'James Doe',
  country: 'Chile',
};

// 👇️ "James Doe"
console.log(obj[str as keyof typeof obj]);

// 👇️ type T = "name" | "country"
type T = keyof typeof obj;
第二种解决方案:
const str = 'name' as string;

interface Person {
  name: string;
  country: string;
}

const obj: Person = {
  name: 'James Doe',
  country: 'Chile',
};

console.log(obj[str as keyof Person]); // 👉️ "James Doe"

// 👇️ type T = "name" | "country"
type T = keyof Person;
第三种解决方案
interface Person {
  name: string;
  country: string;
}

// 👇️ this will only ever be one of object's keys
const str: keyof Person = 'name';

const obj: Person = {
  name: 'James Doe',
  country: 'Chile',
};

console.log(obj[str]); // 👉️ "James Doe"
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值