I am in the process of developing a code generator that creates typescript based on a JSON definition of a data structure. However, I am currently facing an issue when it comes to accessing properties within object arrays in an interface.
Here is an example of the interface causing the problem:
interface SomeComplexThing {
propA: string
propB: number
propC: {
propCA: Array<{
propCA1: string
propCA2: number
}>
}
propD: SomeComplexThing['propC']['propCA']['propCA1'] // Error: Property 'propCA1' does not exist on type '{ propCA1: string; propCA2: number; }[]'
}
When I attempt to access
SomeComplexThing['propC']['propCA']['propCA1']
, I encounter the following error:
Property 'propCA1' does not exist on type '{ propCA1: string; propCA2: number; }[]'
I have discovered that I can access the property by using array indexing like so:
SomeComplexThing['propC']['propCA'][0]['propCA1']
Or even like this:
SomeComplexThing['propC']['propCA'][1234]['propCA1']
It seems inconvenient to have to reference the property inside the array with an arbitrary index value. When generating the code, I may not always know that
SomeComplexThing['propC']['propCA']
is an array type, hence adding [0]
blindly is not feasible as the type could be an object instead.
Is there an alternative approach in Typescript or possibly a utility function that I could utilize to safely access the property without relying on the array index?