javascriptdynamic-properties

How to Create [Key: string] Properly in Typescript?


I want to create this as end result: {"customerName: {"contains": "bri"}}, but I keep getting the name of the variable written instead. I've tried a multitude of things and just can't get it to go as I want. Hoping this is simple and I'm just completely overlooking it.

interface IGraphQLFilterVariable {
  [key: string]: [key: string] | any | IGraphQLFilterVariable[]
}
let property = "customerName";
let type = "contains";
let filter = "bri";

let singleFilter: IGraphQLFilterVariable = {};
singleFilter[property] = {
  type: filter
};
console.log(singleFilter);

Playground


Solution

  • When defining objects, only the values of the objects are expressions by default. The keys are treated as strings, so when you go { type: filter }, it's essentially equivalent to { "type": filter }.

    To use a variable's value as a the key of an object, surround the key in brackets:

    singleFilter[property] = { [type]: filter };
    

    Your object will then look up the value of the variable type and use that as the key for the object.