Index signature for type 'X' is missing in type 'Y' in TS

avatar

Borislav Hadzhiev

Fri Mar 18 20222 min read

Index signature for type 'X' is missing in type 'Y' in TS #

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});.

index signature for type is missing in type

Here is an example of how the error occurs.

index.ts
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.

The index signature in the examples means that when an the object is indexed with a 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.

index.ts
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.

index.ts
// 👇️ 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.

Use the search field on my Home Page to filter through my more than 1,000 articles.