I have implemented a code snippet that sorts items
into groups based on their first character.
For example, if the array of item
looks like this:
- {name: 'Foo'}
- {name: 'Bar'}
- {name: 'Baz'}
The expected result should be:
B: - Bar
- Baz F: - Foo
To achieve this functionality, I am using a computed property in VueJS:
<script lang="ts">
const computedItems = computed(() => {
if (!items.value) return {};
const grouped = items.value.data.reduce((r, item) => {
let group = item.name[0];
if (!r[group]) r[group] = {group, children: [item]}
else r[group].children.push(item);
return r;
}, {});
return Object.keys(grouped).sort().reduce(
(obj, key) => {
obj[key] = grouped[key];
return obj;
},
{} as Record<string, { group: string, children: Item[] }>
);
});
</script>
However, I am encountering this warning:
TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. No index signature with a parameter of type 'string' was found on type '{}'.
This warning is displayed for the following lines:
if (!r[group]) r[group]...
else r[group]...
obj[key] = grouped[key];
The data source for these items is retrieved from an API call:
type ItemResult = { data: ItemData[], links?: any, meta?: any };
const {
data: items,
} = await useLazyAsyncApi<ItemResult>(`/api/item`);
The structure of ItemData
is defined as follows:
export type ItemData = {
uuid: string;
company: App.Domain.Company.Data.CompanyData;
};
export type CompanyData = {
uuid: string;
name: string;
url: string | null;
phone: string | null;
email: string | null;
created_at: string;
deleted_at: string | null;
};
My question is: How can I address the issue where an expression of type 'string' cannot be used as an index here?
Although the code functions correctly, the TypeScript error persists.