carbon-components-svelte icon indicating copy to clipboard operation
carbon-components-svelte copied to clipboard

DataTable: typings for headers and rows

Open albertms10 opened this issue 3 years ago • 1 comments

It would be great if the display and sort method’s parameter types were automatically inferred, somehow. It seems tricky, as having both rows and headers types related would create a circular dependency.

// Typing `headers` with `rows` objects data
const headers = [
  // ...
  {
    key: "quantity",
    value: "Quantity",
    display: (quantity: rows[number]["quantity"]) => quantity + " €",
  },
  {
    key: "date",
    value: "Date",
    display: (date: rows[number]["date"]) => new Date(date).toLocaleString(),
    sort: (a: rows[number]["date"], b: rows[number]["date"]) => new Date(a) - new Date(b),
  },
];

But, in order to force the rows array to have objects with a set of keys defined in headers:

// Typing `rows` with a `headersList` array
const headersList = ["name", "quantity", "date"] as const;

type DataTableRows = {
  [P in typeof headersList[number] | "id"]: string;
};

const rows: DataTableRows = [
  {
    id: 1,
    nam: "John", // Will trigger a TS error
    quantity: 157.89,
    date: "2020-10-21",
  },
];

albertms10 avatar Oct 24 '20 21:10 albertms10