Home > Software design >  TypeScript errors when trying to create product filters
TypeScript errors when trying to create product filters

Time:10-17

I'm working on a product page, with a sidebar that has some product sorting links.

What I've written seems to work, but I'm getting some TypeScript errors that I'm not sure how to fix.

const SORT_KEYS = {
  BEST_SELLING: "Best selling",
  CREATED_AT: "Created at",
  PRICE: "Price",
  PRODUCT_TYPE: "Product type",
  RELEVANCE: "Relevance",
  TITLE: "Title",
  UPDATED_AT: "Updated at",
  VENDOR: "Vendor",
} as const;

type SortKey = keyof typeof SORT_KEYS;
type SortLabel = typeof SORT_KEYS[SortKey];

// Value of `query.sortKey` that comes from `getServerSideProps` in Next.js
let queryKey: string | string[] | undefined;

const sortKey: SortKey | undefined = Object.keys(SORT_KEYS).find(key => key === queryKey);

interface SortLink {
  href: SortKey;
  label: SortLabel;
}

const sortLinks: Array<SortLink> = Object.keys(SORT_KEYS).map((key) => ({
  href: key,
  label: SORT_KEYS[key],
}));

There are two values that I need — sortKey and sortLinks.

sortKey is the value I pass to the GraphQL API which accepts an enum of the values SORT_KEYS (or undefined). The code I've written for this is giving me the following TypeScript error:

Type 'string | undefined' is not assignable to type '"BEST_SELLING" | "CREATED_AT" | "PRICE" | "PRODUCT_TYPE" | "RELEVANCE" | "TITLE" | "UPDATED_AT" | "VENDOR" | undefined'.
  Type 'string' is not assignable to type '"BEST_SELLING" | "CREATED_AT" | "PRICE" | "PRODUCT_TYPE" | "RELEVANCE" | "TITLE" | "UPDATED_AT" | "VENDOR" | undefined'.(2322)

sortLinks are the links that are used in the sidebar. The href property would actually be /products?sortKey=${key}, but just so I understand how to type this properly, I've left it as just the key. Currently this value is coming through as a string, which probably fine for my purposes, my main concern is the label, currently I'm getting the TypeScript error below:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ readonly BEST_SELLING: "Best selling"; readonly CREATED_AT: "Created at"; readonly PRICE: "Price"; readonly PRODUCT_TYPE: "Product type"; readonly RELEVANCE: "Relevance"; readonly TITLE: "Title"; readonly UPDATED_AT: "Updated at"; readonly VENDOR: "Vendor"; }'.
  No index signature with a parameter of type 'string' was found on type '{ readonly BEST_SELLING: "Best selling"; readonly CREATED_AT: "Created at"; readonly PRICE: "Price"; readonly PRODUCT_TYPE: "Product type"; readonly RELEVANCE: "Relevance"; readonly TITLE: "Title"; readonly UPDATED_AT: "Updated at"; readonly VENDOR: "Vendor"; }'.(7053)

I'd really love a bit of help understanding and resolving these issues

  • Related