当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"
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐