Home > Blockchain >  Dynamic properties for a typescript interface
Dynamic properties for a typescript interface

Time:09-16

I wanted to make an interface with dynamic properties, for example with this object:

test: testInterface [];

this.test = [
  {
    name: {
      text: 'something',
      anotherThing: 'something'
    }
  },
  {
    foo: {
      text: 'something',
      anotherThing: 'something'
    }
  },
  {
    whatever: {
      text: 'something',
      anotherThing: 'something'
    }
  },
];

text, foo and whatever (could be any name and the array could have any number of items)

I tried something like this:

export interface testInterface {
  [propName: string]: testSubInterface;
}

interface testSubInterface {
  text: string;
  anotherThing: string;
}

But It doesn't works for me, The final idea is to change the data like this:

this.testInterface.foo.text = "another text for example";

any idea?

CodePudding user response:

Your interface is correct but your object is declared wrongly.

You test should be declared as an object, not an array.

const test: testInterface = {
  name: {
    text: "something",
    anotherThing: "something"
  },
  foo: {
    text: "something",
    anotherThing: "something"
  },
  whatever: {
    text: "something",
    anotherThing: "something"
  }
};

this.testInterface.foo.text = "another text for example";
  • Related