You have the following interface:
export interface XX{
Campo1?: string;
Campo2?: string;
Campo3?: string;
[key: string]: string;
}
The key is to be able to access an element of the same in the form
const p: XX = {};
p['Campo1'];
But the following TS error occurs
Property 'Field1' of type 'string | undefined' is not assignable to string index type 'string' (ts 2411)
Everything goes as if nothing, so I don't know if it's a TS error due to some bug, or I'm simply defining something wrong. How to solve that problem?
The error occurs in the interface definition.
If we change some of the strings to any, the error for that field goes away... but we don't want to use any.
export interface XX{
Campo1?: any; <--- desaparece el error para este campo
Campo2?: string;
Campo3?: string;
[key: string]: string;
}
I have configured ts in the following way (extract)
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"importHelpers": true,
"moduleResolution": "node",
"experimentalDecorators": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"baseUrl": ".",
The problem is in the last line of your definition:
If we look at the documentation we see the following:
That is, if you define that the interface has properties that store values that are
string
(like this[key: string]: string;
), ALL properties must comply with this. Since itCampo1
has a question mark (it can be string or undefined), it does not meet the condition.You can fix it like this:
Another option would be to relax the compiler checks:
or also
You have the option
strictNullChecks
enabled. When you do this it changes the way typescript handles types as itundefined
is normally considered a subset of all types to better resemble the default behavior of javascript.In other words, when in Typescript you say you're
a: string
really sayinga: string | undefined
so this code is perfectly validWhen you enable strict mode
undefined
it is only assignable to itself (same asnull
).The problem then arises indirectly because you are making your
Campo1
,Campo2
, etc properties optional(?
) which is the same as sayingIn fact if you try that code the error will be identical.
If you try to remove the optional fields the error disappears
So it all boils down to the fact that the indexed property
[key: string]: string
also matches yourCampo1
,Campo2
, etc properties and the types are not compatible.The solutions I recommend are:
Extend the type a
string | undefined
for the indexed property so its signature matches that of the optional typesRemove the
Campo1
,Campo2
, etc properties because your interface is equivalent to just using this anyway and when all properties are optional type-checking doesn't really help much except for intellisense.