const test = [
{
"a": 1
},
{
"b": 1
}
]
interface t {
[key: string]: number
}
const ttt: t[] = test
Property '"b"' is incompatible with index signature. Type 'undefined' is not assignable to type 'number'. it works if I rename the key either b or a both of same key.
Index signature is used to represent the type of object/dictionary when the values of the object are of consistent types. Syntax: { [key: KeyType] : ValueType } Assume that we have a theme object which allows us to configure the color properties that can be used across the application.
Index signature syntax The syntax of an index signature is pretty simple and looks similar to the syntax of a property, but with one difference. Instead of the property name, you simply write the type of the key inside the square brackets: { [key: KeyType]: ValueType } .
The indexing type is itself a type, so we can use unions, keyof , or other types entirely: type I1 = Person ["age" | "name"]; type I1 = string | number. type I2 = Person [keyof Person ]; type I2 = string | number | boolean.
The "Type 'string' is not assignable to type" TypeScript error occurs when we try to assign a value of type string to something that expects a different type, e.g. a more specific string literal type or an enum. To solve the error use a const or a type assertion.
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.
The index signature in the example means that when an the object is indexed with a 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.
Property 'baseSalary' is incompatible with index signature. Type 'string' is not assignable to type 'number'. 2. Index signature syntax The syntax of an index signature is pretty simple and looks similar to the syntax of a property, but with one difference.
This behavior suggests that the index signature is meant to be generic in regards to keys. But you can use a union of string literals to describe the keys in a Record<Keys, Type>: The Record<Keys, Type> is meant to be specific in regards to keys. I recommend using the index signature to annotate generic objects, e.g. keys are string type.
Because test
doesn't have a type, it's being inferred to this type:
({ a: number; b?: undefined; } | { b: number; a?: undefined; })[]
test
is then assigned to ttt
, but it's not compatible to have a possibly undefined b
key in the new interface t
.
You can fix this by add the type directly to test
:
const test: t[] = [
{
"a": 1
},
{
"b": 1
}
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With