如何基于枚举为 .reduce 创建初始值?

How to create initial value for .reduce based on enum?

我有一个简化的函数,它需要基于枚举的初始值。请参阅下面的简化代码:

items.reduce<Record<RoleType, Community[]>>(
    (acc, community) => {
        ... // this works
    },
    { [RoleType.LEADER]: [], [RoleType.FACILITATOR]: [], [RoleType.EDITOR]: [], [RoleType.EXPERT]: [], [RoleType.MEMBER]: [] }
);

枚举如下所示:

export enum RoleType {
    EXPERT = 'EXPERT',
    LEADER = 'LEADER',
    FACILITATOR = 'FACILITATOR',
    EDITOR = 'EDITOR',
    MEMBER = 'MEMBER'
}

虽然我不想明确列出枚举的每个成员。我尝试了以下内容:

{ ...Object.values(RoleType).map((role) => ({ [role]: [] })) }

有没有办法简单地为所有枚举成员添加空数组?最好的情况是也有正确的输入。

我上面的尝试抛出了这个错误(我真的不知道该怎么办):

Type '{ [n: number]: { [x: string]: any[]; }; length: number; toString(): string; toLocaleString(): string; pop(): { [x: string]: any[]; }; push(...items: { [x: string]: any[]; }[]): number; concat(...items: ConcatArray<{ [x: string]: any[]; }>[]): { ...; }[]; concat(...items: ({ ...; } | ConcatArray<...>)[]): { ...; }[];...' is missing the following properties from type 'Record<RoleType, Community[]>': EXPERT, LEADER, FACILITATOR, EDITOR, MEMBER

{ ...Object.values(RoleType).map((role) => ({ [role]: [] })) }

将创建一个以数组索引为键的对象。

{
  "0": { "EXPERT": [] },
  "1": { "LEADER": [] },
  "2": { "FACILITATOR": [] }
  ...
}

你需要使用这样的东西:

Object.assign({}, ...Object.values(RoleType).map(r => ({ [r]: [] })))

我制作了一个 TS 转换器,它允许您抓取枚举的所有值 - 它被称为 ts-reflection,它的工作原理如下:

enum MyEnum {
  NO = 0,
  MAYBE = 1,
  YES = 2
}

const valuesOfMyEnum = valuesOf<MyEnum>(); // [0, 1, 2]

Here's how you set it up