Categories
TypeScript Answers

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

Spread the love

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: "jane",
  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.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published. Required fields are marked *