Categories
TypeScript Answers

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

Spread the love

To fix No index signature with a parameter of type ‘string’ was found on type ‘{ "A": string; } with TypeScript, we can use the keyof operator to set the type of the key we use to access an object’s property is actually in the object.

For instance, we write

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

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

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

to define the getValue function that takes the key parameter.

We set the key parameter to keyof User so that the value of key can only be the property keys listed in the User interface.

Then we can access the properties of user with key without compiler errors.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.