Borislav Hadzhiev
Fri Mar 18 2022·2 min read
Photo by Tong Nguyen van
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, e.g. accessEmployee({...employee});
.
Here is an example of how the error occurs.
interface Employee { name: string; country: string; } const employee: Employee = { name: 'James', 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: 'James', country: 'Germany', }; const accessEmployee = (employee: { [key: string]: string }) => { return employee['country']; }; // ✅ Works now accessEmployee({ ...employee }); // 👉️ "Germany"
Note that this limitation does not exist when using type aliases.
// 👇️ Now using type alias type Employee = { name: string; country: string; }; const employee: Employee = { name: 'James', 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.