carbon-components-svelte
carbon-components-svelte copied to clipboard
feat: improve typing for DataTable row and cell
fix #667 (maybe)
Thank you for such a nice library :tada:
When using DataTable component, it would be great if the editor autocompletes headers
prop or slot values(cell.key
or row
).
I make it possible with Generics(named Row
). For example,
export interface DataTableEmptyHeader<Row extends DataTableRow = DataTableRow>
extends DataTableRow
restrict Row type (e.g. it should have id
property). = DataTableRow
is to avoid breaking change.
Feel free to:
- Close this PR if not suitable.
- Change my code.
without say anything.
demo (autocomplete is working correctly by this PR)
https://user-images.githubusercontent.com/40315079/133122454-829fbe75-b052-44f1-8230-f3eca94640cc.mp4
code in demo
<script>
import { DataTable } from "carbon-components-svelte";
const rows = [
{ id: 1, name: "user1", age: 10, gender: "male" },
{ id: 2, name: "user2", age: 20, gender: "female" },
];
</script>
<DataTable
rows="{rows}"
headers="{[{ key: 'name', value: 'Name' }, { key: 'age', value: 'Age' }, { key: 'gender', value: 'Gender' }]}"
>
<div slot="cell" let:cell let:row>
{#if cell.key === 'age'}{row.age}(years old){:else}{cell.value}{/if}
</div>
</DataTable>
Started testing locally – this looks very promising!
This may also address this issue: https://github.com/carbon-design-system/carbon-components-svelte/issues/364
There is a bit of wrinkle with key: keyof Row;
in that keys can also access nested objects or not exist at all. But I would love to have generics for the slot properties, otherwise it requires a lot of type assertions when working in TypeScript.
REPL demonstrating other key uses
Using interpolated string literal types it it actually possible to get nested keys as well. The types may be a bit hard to read and it does not handle the synthetic keys case, though.
TS Playground example for nested key resolution
(This pull request does not fix #667, because that issue is about the runtime type.)