How to fix the “TypeScript: No index signature with a parameter of type ‘string’ was found on type ‘{ “A”: string; }” error with TypeScript?

Sometimes, we want to fix the “TypeScript: No index signature with a parameter of type ‘string’ was found on type ‘{ “A”: string; }” error with TypeScript.

In this article, we’ll look at how to fix the “TypeScript: No index signature with a parameter of type ‘string’ was found on type ‘{ “A”: string; }” error with TypeScript.

How to fix the “TypeScript: No index signature with a parameter of type ‘string’ was found on type ‘{ “A”: string; }” error with TypeScript?

To fix the “TypeScript: No index signature with a parameter of type ‘string’ was found on type ‘{ “A”: string; }” error with TypeScript, we can use the keyOf operator to use the values of the keys of an object as the type.

For instance, we write

interface User {
  name: string;
  age: number;
}

const user: User = {
  name: "someone",
  age: 20,
};

const getValue = (key: keyof User) => {
  return user[key];
};

to set the getValue function’s key parameter’s type to keyof User.

This means the value of key van be 'name' or 'age'.

Then we can use key in our function to get a value from user.

Conclusion

To fix the “TypeScript: No index signature with a parameter of type ‘string’ was found on type ‘{ “A”: string; }” error with TypeScript, we can use the keyOf operator to use the values of the keys of an object as the type.