当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"
GitHub 加速计划 / eleme / element
14
1
下载
A Vue.js 2.0 UI Toolkit for Web
最近提交(Master分支:1 个月前 )
c345bb45 1 年前
a07f3a59 * Update transition.md * Update table.md * Update transition.md * Update table.md * Update transition.md * Update table.md * Update table.md * Update transition.md * Update popover.md 1 年前
Logo

新一代开源开发者平台 GitCode,通过集成代码托管服务、代码仓库以及可信赖的开源组件库,让开发者可以在云端进行代码托管和开发。旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐