Home > Net >  Typescript construct giving error when calling values
Typescript construct giving error when calling values

Time:01-07

I have defined my typescript object like this:

interface myInterface {
    obj1: string;
    obj2 : string,
}

const myValues : {[stage : string]:{[region : string]:myInterface}} = {
    'beta':{
        'us-east-1':{
            obj1: "random_a1",
            obj2: "random_a2"
        },
        'eu-west-1':{
            obj1: "random_b1",
            obj2: "random_c1"
        }
    },
}

Now this is how I want to access the values, but I am getting error. How should I change my values so that I can call values like this:

let x = myValues[stage]?[region];

CodePudding user response:

let x = myValues[stage]?.[region];

CodePudding user response:

I don't know if I understood your question well, but I believe I can return something using this

interface myInterface {
    obj1: string
    obj2: string
  }

  const stage1 = 'us-east-1'

  const myValues: { [stage: string]: { [region: string]: myInterface } } = {
    beta: {
      'us-east-1': {
        obj1: 'random_a1',
        obj2: 'random_a2',
      },
      'eu-west-1': {
        obj1: 'random_b1',
        obj2: 'random_c1',
      },
    },
  }

  console.log(myValues.beta[stage1])
  • Related