【问题标题】:Converting an array of string to a dictionary将字符串数组转换为字典
【发布时间】:2021-06-23 05:10:25
【问题描述】:

我希望能够将字符串数组转换为字典,传入的字符串成为对象的键(并且值设置为true):

// obj = { foo: true, bar: true );
const obj = toObject("foo", "bar");

这在运行时使用 JS 非常简单,但我希望将类型保留在 TS 中,这非常具有挑战性。这是一个在运行时工作但最终以all 类型转储对象的实现。呸。

function toObject<T extends readonly string[]>(...keys: T) {
  return keys.reduce((acc, k) => {
    acc[k] = true;
    return acc;
  }, {} as any);
}

使用all,我们的值为零,但它仍然比在reducer 中不声明as any 好。至少我们可以在运行时索引字典。如果我们不理会它,该类型将是一个空对象。相反,我需要某种将字符串数组转换为字符串并集的方法。一旦我有了它,我可以简单地将减速器的初始状态输入到:

{} as Record<UnionOfStrings, true>;

也就是说,我不知道如何进行这种转换。

有人知道吗?

【问题讨论】:

  • const arr = ["foo", "bar"] as const; type Union = typeof arr[number];

标签: typescript typescript-typings typescript-generics


【解决方案1】:

您实际上不需要为此使用.reduce,因为它实际上并不比仅使用普通的for 循环简单得多。这是我使用for 循环编写的实现,但如果您愿意,也可以使用.reduce 编写。

function toObject<T extends readonly string[]>(...keys: T): Record<T[number], true> {
    const obj: Record<string, true> = {};

    for (const key of keys) {
        obj[key] = true;
    }

    return obj;
}

注意返回类型:Record&lt;T[number], true&gt;。我想这就是你要找的。​​p>

【讨论】:

  • 啊哈;很高兴使用任何循环结构,但 Record&lt;T[number], true&gt; 是一个宝石。
猜你喜欢
  • 1970-01-01
  • 2020-09-16
  • 2012-09-07
  • 2010-12-10
  • 1970-01-01
  • 1970-01-01
  • 2022-07-24
  • 2021-07-25
相关资源
最近更新 更多