First time trying out something in Typescript and running into a very trivial but very annoying problem.
The problem is reading json sub-documents. The input data looks something like
[{
"json": {
"jsonKeyName": "keyValue",
"body": {
"name": "test",
"age": 32
}
}
}
]
Data Structures that define the above data are given below. This part is outside of my control
export type GenericValue = string | object | number | boolean | undefined | null;
export interface IDataObject {
[key: string]: GenericValue | IDataObject | GenericValue[] | IDataObject[];
}
export interface INodeExecutionData {
[key: string]: IDataObject | IBinaryKeyData | undefined;
json: IDataObject;
binary?: IBinaryKeyData;
}
I want to read the fields name
and age
inside the sub-document.
Simple code that I am trying looks something like
const items = this.getInputData();
let item: INodeExecutionData;
for (let itemIndex = 0; itemIndex < items.length; itemIndex++) {
item = items[itemIndex]
const name = item.json['body']['name']
}
This gives the following errors
Error:(71, 17) TS2533: Object is possibly 'null' or 'undefined'.
Error:(71, 17) TS7053: Element implicitly has an 'any' type because expression of type '"name"' can't be used to index type 'string | number | boolean | object | IDataObject | GenericValue[] | IDataObject[]'.
Property 'name' does not exist on type 'string | number | boolean | object | IDataObject | GenericValue[] | IDataObject[]'.
I tried to get rid of the first issue by changing the logic to
const body = item.json['body']
const name = (body || {})['name']
Even in this case, I still get the error
Error:(72, 19) TS7053: Element implicitly has an 'any' type because expression of type '"name"' can't be used to index type 'string | number | true | object'.
Property 'name' does not exist on type 'string | number | true | object'.
What am I missing here.