The error “Index signature for type ‘string’ is missing in type” occurs in TypeScript when we are trying to access a property using a dynamic string, but the object type doesn’t define an index signature to accommodate that.
For Example, The above Error will come in the following scenario
index.ts
type Person = {
name: string;
age: number;
};
const person: Person = { name: "Joy", age: 20 };
const key = "email";
console.log(person[key]); // Error: Index signature is missing
In the above example, typescript throws an error because key could be any string, but the Person type only explicitly defines name and age. To fix this we can add an index signature to the type as follows.
index.ts
type Person = {
name: string;
age: number;
[key: string]: string // index signature allows only string values
};
const person: Person = { name: "Joy", age: 20, email: "joy@gmail.com" };
const key= "email";
console.log(person[key]); // No Error