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

The full error message is this:

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

This error generally occurs in the scene where the object is used to obtain the value.

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];

We only need to ensure that str is the key of obj to avoid error reporting. Commonly used methods are as follows:

method one:

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]);

Method Two:

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

const str = 'name' as string;

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

It can be seen that these two methods are very similar. The reason why typeof is not used here is because Person is the type we defined, not an object. The results obtained by the two methods are the same.

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

Of course, if str does not use type assertion, there is no problem in writing this way, as follows:

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

const str = 'name';

console.log(obj[str]);

Well, let's consider another scenario. If I have many attributes in the obj object, I will use the keys in the obj object in many places. I can't all be keyof or keyof typeof. Is there any better? What about the plan?

Method 3:

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

const str: keyof Person = 'name';

console.log(obj[str]);

What if I want to add an attribute to obj? Adding directly will definitely report an error, as follows:

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';

When you are not sure whether the value of the key exists in the obj object, you can use the following method:

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

Guess you like

Origin blog.csdn.net/weixin_38629529/article/details/127131932