-2

I'm using ReactJs with typescript and I need to create a dynamic object interface for example:

language: {name: string}

but I need the language key to be dynamic. for example: I need to be able to add an object like below to the state

en_us: {name: english}
  • 1
    You should be able to do that using [] – brk Aug 26 '20 at 05:36
  • Does this answer your question? [Add a property to a JavaScript object using a variable as the name?](https://stackoverflow.com/questions/695050/add-a-property-to-a-javascript-object-using-a-variable-as-the-name) – John Ruddell Aug 26 '20 at 05:38
  • 1
    Check this: https://stackoverflow.com/questions/12710905/how-do-i-dynamically-assign-properties-to-an-object-in-typescript – Jayasanka Weerasinghe Aug 26 '20 at 14:44

1 Answers1

0

You can use brackets to define object keys as [name: type]:

type language = {
  [langCode: string]: { // this allows you to use any string as key
    name: string
  }
}

const languages: language[] = [
  { en_us: { name: "english" } },
  { pt_br: { name: "brazilian-portuguese"} }
]
dalmo
  • 443
  • 3
  • 11