Last updated: Feb 29, 2024
Reading timeยท3 min
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: 'Bobby Hadz', }; // โ๏ธ 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: 'Bobby Hadz', }; 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
.
any
typeIf 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, set the type in the
index signature to any
.
type Employee = { [key: string]: any; }; const dev = { salary: 100, name: 'Bobby Hadz', 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: 'Bobby Hadz' }; // โ๏ธ 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 to 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);
You can learn more about the related topics by checking out the following tutorials: