Instantiate a new keyValuePair and add an existing dictionary in Type Script

18 views Asked by At

I defined a new dictionary class but I am not sure how to define the Dictionary attribute. There's a json file called Switches:

{"ShowImage": true,"ShowText": false, "showButton", true}

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

export class DictionaryClass{
    Dictionary?: { [key: string]: boolean };
}

export function getDictionary() {

   const dictionaryClass = new DictionaryClass();
   dictionaryClass.Dictionary = { [key: string]: boolean };
    for (let entry in switches) {
        dictionaryClass.Dictionary[entry] = switches[entry];
    }
return dictionaryClass;

}

In this example, I am not sure how to instantiate dictionary, and this is one way I tried that doesn't work:

const dictionaryClass = new DictionaryClass();
dictionaryClass.Dictionary = { [key: string]: boolean };

I also tried to do the following but it doesn't work either

  const dictionaryClass = new DictionaryClass();
  dictionaryClass.Dictionary = switches;

Could someone point it to me how to instantiate it properly? Also, instead of looping the json dictionary, is there anyway to append this whole json dictionary to this dictionary object?

1

There are 1 answers

0
Linda Paiste On

Honestly there is no point in using a class here since your class doesn't do anything.

What you want is a type that defines the shape of a dictionary, which is what you have here:

type BooleanDictionary = { [key: string]: boolean }

All of this other stuff is completely unnecessary because your JSON already fits that type on its own! That's the advantage of making code that relies on types and interfaces instead of specific classes.

Playground Link