Как реализовать сортировку . Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'IGoods'

Рейтинг: -1Ответов: 1Опубликовано: 27.02.2023

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'IGoods'.
No index signature with a parameter of type 'string' was found on type 'IGoods'.

Я так понял, когда пытаюсь обратиться к ключу объекта через b[selectOption], он его не находит, т.к. я передаю строку?
Но тогда не пойму как вытянуть значение и отсортировать.
Есть формула, которая должна возвращать отсортированный список объектов в массиве. для начала интерфейсы:

1.Для сортировки. Значения инпута и селекта

export interface ISearchOptions {
    inputText:string,
    selectOption:any,
}

2.Для объекта

export interface IGoods{
    id: string,
    title: string,
    description:string,
    price: number | undefined | string,
    discountPercentage: number | undefined | string,
    rating: number | undefined | string,
    stock: number | undefined | string,
    brand: string,
    category: string,
    thumbnail: null | string,
}

Сам хук

export const useSorted = (productList: IGoods[] | undefined, 
    selectOption:string) => {
    const sortedProducts = useMemo(()=>{
        if(productList){
            if(selectOption) {
               return 
    productList.sort((a,b)=>a[selectOption].localeCompare(b[selectOption]));
            } else {
                // return productList;
            }
            }
        },[productList, selectOption])
    return sortedProducts;
}

Пытаюсь получить сортированные или же массив без сортировки

const newArray =  useSorted(data, searchOptions.selectOption)
searchOptions.selectOption = 'title' или 'brand'

Ответы

▲ -1

Решил проблему через [...productList].sort:


export const useSorted = (productList: IGoods[] | undefined, selectOption: keyof IGoods) => {
    const sortedProducts = useMemo(() => {
        if(productList?.length){
            if(selectOption) {
               return [...productList].sort((a,b)=>a[selectOption].localeCompare(b[selectOption]));
            } else {
                return productList;
            }
        }
    },[productList, selectOption])
    return sortedProducts;
}