Last updated: Feb 28, 2024
Reading time·2 min
The error "Index signature for type is missing in type" occurs when TypeScript doesn't consider a type that uses an index signature and a more specific type to be compatible.
To solve the error, use the spread syntax (...) when calling the function.
Here is an example of how the error occurs.
interface Employee { name: string; country: string; } const employee: Employee = { name: 'Bobby Hadz', country: 'Germany', }; const accessEmployee = (employee: { [key: string]: string }) => { return employee['country']; }; // ⛔️ Error: Index signature for type 'string' // is missing in type 'Employee'.ts(2345) accessEmployee(employee);
The accessEmployee
function takes an object that contains an
index signature as a parameter.
string
, it will return a string
.The Employee
interface defines an object with name
and country
properties
of type string
.
Unfortunately, TypeScript considers the much more specific Employee
type to
not be compatible with the index signature.
The easiest way to get around this is to use the spread syntax (...) to create a shallow copy of the object and make TypeScript recognize it is of a compatible type.
interface Employee { name: string; country: string; } const employee: Employee = { name: 'Bobby Hadz', country: 'Germany', }; const accessEmployee = (employee: { [key: string]: string }) => { return employee['country']; }; // ✅ Works now accessEmployee({ ...employee }); // 👉️ "Germany"
I've also written an article on how to create a deep copy of an object.
Note that this limitation doesn't exist when using type aliases.
// 👇️ Now using type alias type Employee = { name: string; country: string; }; const employee: Employee = { name: 'Bobby Hadz', country: 'Germany', }; const accessEmployee = (employee: { [key: string]: string }) => { return employee['country']; }; // ✅ Works now accessEmployee(employee); // 👉️ "Germany"
This is not a bug but is by design and was done because interfaces can be augmented by additional declarations and type aliases cannot.
Type aliases cannot be augmented, so it's "safer" to infer an implicit index signature for a type alias than an interface.
If you want to read more on the topic, check out this GitHub issue in the TypeScript repository.
You can learn more about the related topics by checking out the following tutorials: