How can i define a dynamic key for an object

Hey, im learning the language but i found myself in a very silly problem. Here’s the code:

let generateEnumString = (names: array<string>, propName: string) =>
  names->Array.mapWithIndex((name, index) => {"id": index, `${propName}`: name})

I have this function that create an enum and i want it to have an dynamic property, but the compiler doesnt accept it. The use case would be like this:

let PersonNames = generateEnumString(["John", "Annie", "Mary"], "personName") // {id:1, personName:"Annie"}

let ColorList = generateEnumString(["Blue", "Red", "Black"], "color") // {id:1,"color":"Red"}

I feel that the problem is very simple but i still cant find the solution

You can’t generate types on the fly. You could do it like this though:

let generateEnumString = (names: array<string>, propName: string): array<
> =>
  names->Belt.Array.mapWithIndex((index, name) => {
    let result = Js.Dict.empty()
    result->Js.Dict.set("id", index->string_of_int)
    result->Js.Dict.set(propName, name)

let personNames = generateEnumString(["John", "Annie", "Mary"], "personName") // {id:1, personName:"Annie"}

let colorList = generateEnumString(["Blue", "Red", "Black"], "color") // {id:1,"color":"Red"}

let blue = colorList->Belt.Array.get(0)->Js.Option.getExn->Js.Dict.get("color")
1 Like