TS4111 - noPropertyAccessFromIndexSignature
While working on an Angular version of our popular Gantt chart demonstration this morning I stumbled across a Typescript linting issue whose purpose is not at all clear to me.
Say I have this interface for a person:
export interface Person {
firstName:string
lastName:string
}
and this for a serialized person:
export interface Person {
firstName:string
lastName:string
fullName:string
}
Now I want to write a serializer to export a bunch of these people:
export function serializePeople(persons:Array<Person>):string {
return persons.map(p => {
return {
fullName:`${p.firstName} ${p.lastName}`,
firstName:p.firstName,
lastName:p.lastName
}
})
}
This looks ok, right? Well in fact the default settings for Angular's tsconfig.json cause an error:
Property 'firstName' comes from an index signature, so it must be accessed with ['firstName']
Huh? Is it not the case that if I were to switch to the suggested way to access the property I would lose type checking? This seems like nonsense to me. I could rewrite my serializer to this, yes:
export function serializePeople(persons:Array<Person>):string {
return persons.map(p => {
return {
fullName:`${p['firstName']} ${p['lastName']}`,
firstName:p.firstName,
lastName:p.lastName
}
})
}
...and I could also rewrite it to this, which would compile, but fail at runtime with a null pointer exception:
export function serializePeople(persons:Array<Person>):string {
return persons.map(p => {
return {
fullName:`${p['firstName']} ${p['lastName']}`,
firstName:p.firstName,
lastName:p.lastName,
lengthOfUnknownField:p['someUnknownField'].length
}
})
}
It isn't clear to me what the purpose of this linting rule is. The reason people move to Typescript is exactly to get away from situations like this.
THE FIX
Fortunately the fix for this is straightforward - look for noPropertyAccessFromIndexSignature in your tsconfig.json and set it to false:
"compilerOptions": {
...
"noPropertyAccessFromIndexSignature":false
...
}
Start a free trial
Get in touch!
If you'd like to discuss any of the ideas/concepts in this article we'd love to hear from you - drop us a line at hello@jsplumbtoolkit.com.