【问题标题】:How to Create [Key: string] Properly in Typescript?如何在 Typescript 中正确创建 [Key: string]?
【发布时间】:2021-03-12 21:04:24
【问题描述】:

我想将其创建为最终结果:{"customerName: {"contains": "bri"}},但我不断得到写入变量的名称。我已经尝试了很多事情,但无法让它如我所愿。希望这很简单,我只是完全忽略了它。

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

【问题讨论】:

标签: javascript dynamic-properties


【解决方案1】:

定义对象时,默认只有对象的是表达式。键被视为字符串,因此当您转到{ type: filter } 时,它基本上等同于{ "type": filter }

要将变量的值用作对象的键,请将键括在括号中:

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

然后,您的对象将查找变量 type 的值并将其用作对象的键。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-31
    • 2020-04-12
    • 1970-01-01
    • 2017-12-21
    • 2018-12-08
    • 1970-01-01
    • 2021-04-10
    • 2010-10-21
    相关资源
    最近更新 更多