Borislav Hadzhiev
Tue Mar 22 2022·2 min read
Photo by Anthony Tran
The error "Property is incompatible with index signature" occurs when a property is not compatible with the specified type of the index signature. To solve the error, change the type of the property or use a union to update the type in the index signature.
Here is an example of how the error occurs.
type Employee = { [key: string]: string; }; const dev = { salary: 100, // 👈️ this is a number name: 'Bob', }; // ⛔️ Error: Property 'salary' is incompatible with index signature. const emp1: Employee = dev;
The {[key: string]: string}
syntax is an
index signature
in TypeScript and is used when we don't know all the names of a type's
properties ahead of time, but know the shape of the values.
string
key, it will return a value of type string
.However, notice that the salary
property in the object has a value of type
number
. This causes the error, because the type of the salary
property is
incompatible with the index signature.
One way to solve the error is to use a union type to widen the type of the values in the index signature.
type Employee = { [key: string]: string | number; // 👈️ now takes string or number }; const dev = { salary: 100, name: 'Bob', }; const emp1: Employee = dev;
We don't get the error anymore, because now the index signature in the
Employee
type means that when the object is indexed with a string
key, it
will return a value of type string
or number
.
If you don't know the names of the properties or the type of the values your
object will contain and want to turn off type checking, you can set the type in
the index signature to any
.
type Employee = { [key: string]: any; }; const dev = { salary: 100, name: 'Bob', tasks: ['develop', 'test'], }; const emp1: Employee = dev;
This approach enables you to add properties of any type to the object, but it disables type checking.
Here is another example of how the error occurs.
type Employee = { [key: string]: string; }; function example(emp: Employee) { return emp; } const emp2 = { id: 1, name: 'Alice' }; // ⛔️ Property 'id' is incompatible with index signature. example(emp2);
The index signature in the Employee
type only allows values of type string
,
however the id
property in the object has a value of number
.
To solve the error, we either have to widen the type in the index signature or
set the id
property a string value in the object.
type Employee = { [key: string]: string | number; // 👈️ widen type }; function example(emp: Employee) { return emp; } const emp2 = { id: 1, name: 'Alice' }; // ✅ works now example(emp2);