1

I am newbie in typescript so not really good in syntax.

My requirement is I want to get some specific elment from json file in typescript.

Following is piece of code that I am trying here.

Json file

{
"Description": "data",
"data_list": {
  "example1": {
    "description": "example1",
    "anothermap":{
       "a": "1",
       "b": "2"
    }
 },
 "example2": {
    "description": "example2"
 }
}

}

Typescript file

import * as test from '../test.json';

export class Demo extends cdk.Stage {

  constructor(scope: cdk.Construct, id: string, name: string) {
    super(scope, id);

    #const tskData = test.data_list['example1'];
    const tskData = test.data_list[name];
}

in the above example when I try to call json value using literals then it works but not with varible. I can't use any literal here becuase what system needed will come as input.

Following is the error that I am getting it

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '

Any help on this would be appriciated

1
  • Error when trying to acccess another map : Property 'anothermap' does not exist on type '{ description: string; Commented Mar 2, 2022 at 12:37

1 Answer 1

1

Typescript determines the json's type from it's structure.

You're trying to index test.data_list with any string, but not all strings in the world are present as keys in the json. Try changing name's type to name: "example1" | "example2"

Or you can automatically create type for possible name values with type NameType = keyof typeof test.data_list; and then simply write name: NameType.

Sign up to request clarification or add additional context in comments.

3 Comments

I think this second approach works for me and able to access json data as varible. But my example wasn't simple as I paste here so edit it again.
json has been edit and now facing another issue while access another map inside the element. Can you help me on this ?
Sorry, I thought I could help because I faced a similar issue, but I will leave this to someone more qualified.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.