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
.