1

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.

auny
  • 1,920
  • 4
  • 20
  • 37
  • If you're sure item.json['body'] can't be null, you can use [the non-null assertion operator](https://stackoverflow.com/questions/42273853/in-typescript-what-is-the-exclamation-mark-bang-operator-when-dereferenci) to fix the first error. But be careful there...you might want to do an actual null-check instead. – temporary_user_name Jan 08 '20 at 04:21
  • As for the second error, you need to share the actual code or something. Obviously `tenant` does not show up in the code snippet you have shared, so it's hard to troubleshoot. I can tell you at least that the error seems to think you're indexing into a type, rather than into an object with a type. – temporary_user_name Jan 08 '20 at 04:22
  • I have fixed the errors. It was a copy/paste mistake. – auny Jan 08 '20 at 05:53

0 Answers0