Typescript: union type with index

Viewed 142

I'm working on some pagination config for a table and trying to create proper types for my request. Here are my types:

interface Data {
  prop1: number;
  prop2: string;
}

interface Sort<T> {
  order_by: keyof T;
  sort_order: "asc" | "desc";
}

interface Filters {
  [key: string]: React.Key[];
}

interface Pagination {
  page: number;
  page_size: number;
}

type Request<T> = Sort<T> & Pagination & Filters;

Later I'm creating objects of each type and trying to put them all together:

const sort: Sort<Data> = {order_by: 'prop1', sort_order: "asc"}
  const pagination: Pagination = {page: 1, page_size: 10}
  const filters:Filters = {prop1: [2, 55]}

  const request: Request<Data> = {
    ...sort,
    ...pagination,
    ...filters
  }

But it throws an error:

Type '{ page: number; page_size: number; order_by: "prop1" | "prop2"; sort_order: "asc" | "desc"; }' is not assignable to type 'Request<Data>'.
  Type '{ page: number; page_size: number; order_by: "prop1" | "prop2"; sort_order: "asc" | "desc"; }' is not assignable to type 'Filters'.
    Property 'page' is incompatible with index signature.
      Type 'number' is not assignable to type 'Key[]'.

I was also trying to use Exclude and Omit utility types on Filter to remove the keys of other 2 types, but that didn't help much.

Is there a way to achieve what I want without manually setting keys in Filters?

0 Answers
Related