[Vuejs]-TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'

1👍

I assume you’re missing a type on your first reduce() call, as Typescript cannot know that your {} reduce initializer is of type Record<string, { group: string, children: Item[] }> :

    const grouped = items.value.data.reduce((r, item) => {
        let group = item.name[0];
        r[group] = r[group] || {group, children: []}
        r[group].children.push(item);
        return r;
    }, {} as Record<string, { group: string, children: Item[] }>); // <- HERE
    return Object.keys(grouped).sort().reduce(
        (obj, key) => {
            obj[key] = grouped[key];
            return obj;
        },
        {} as Record<string, { group: string, children: Item[] }>
    );

Aside from your question, you can sort() your data first, which will avoid a second pass on grouped result :

    const grouped = items.value.data
       .sort((i1, i2) => i1.name.localeCompare(i2.name))
       .reduce((r, item) => {
          let group = item.name[0];
          r[group] = r[group] || {group, children: []}
          r[group].children.push(item);
          return r;
       }, {} as Record<string, { group: string, children: Item[] }>);

Leave a comment