table icon indicating copy to clipboard operation
table copied to clipboard

Typescript Discussion

Open hassankhan opened this issue 7 years ago • 66 comments

Hi all,

I'd like to start by saying thank you to all the maintainers and contributors of this package 💯 and also apologies for not using the issue template format, wasn't quite sure if this was a bug or a feature request.

I've been trialling the v7 branch, and overall its really really impressive 🙌 The only part that seemed a little ... lacking was the Typescript types. This was not a huge issue, as I was able to create my own types file that the compiler merges with the types provided by react-table (using declaration merging)

I noticed that beta 12 has recently been released, and I updated (from beta 10). Unfortunately, it seems that the situation has somewhat worsened from a developer experience perspective. I'm assuming the changes were made in order to better handle the fact that any number of plugin hooks might be specified by a user. However, these changes seem to have come at the cost of requiring users to include a custom types file in their projects (which is a little unusual, even for Typescript projects).

In an ideal world, it'd be great to see react-table written natively in Typescript to avoid situations where the code and types are not in sync, but I do understand that might not be what the maintainers/contributors want. That said, the procedure in beta 12 seems like it could be improved, and I'm happy to help 😄 I'm including my additions to the types file from beta 10 that mostly fixed the plugin issues, as well as adding a few other missing types. There are some definite improvements in the beta 12 types, so it'd be good to see if we can find some middle ground.

import {
  Row,
  TableInstance,
  TableOptions,
  useGroupBy,
  useFilters,
  useSortBy,
  useExpanded,
  usePagination,
  useRowSelect,
  useRowState,
  useColumnOrder,
  useBlockLayout,
  useAbsoluteLayout,
  useResizeColumns,
  Column,
} from "react-table";

declare module 'react-table' {
  export interface TableInstance<D = {}> extends TableOptions<D> {
    getTableBodyProps: (userProps?: any) => any
    selectedFlatRows: Row<D>[]
  }

  export interface HeaderColumn<D> {
    disableFilters?: boolean;
  }

  export interface EnhancedColumn<D>
    extends Omit<Column<D>, 'columns'>,
      TableInstance<D> {
    canFilter?: boolean
  }

  export interface UsePaginationValues<D = {}> {
    pageOptions: number[]
  }

  export type Plugin<D> = useGroupBy<D> |
    useFilters<D> |
    useSortBy<D> |
    useExpanded<D> |
    usePagination<D> |
    useRowSelect<D> |
    useRowState<D> |
    useColumnOrder<D> |
    useBlockLayout<D> |
    useAbsoluteLayout<D> |
    useResizeColumns<D>

  export function useTable<D = {}, P = Plugin<D>>(
    props: TableOptions<D>,
    ...plugins: P[]
  ): TableInstance<D> & ReturnType<typeof P>

  export function useRowSelect<D = {}>(
    props: TableOptions<D>
  ): TableOptions<D>
}

hassankhan avatar Oct 12 '19 00:10 hassankhan

I'm confused as to what you're saying is missing/worse?

canFilter, disableFilter are still in a PR. I added getTableBodyProps and can't remember if selectedFlatRows was added off the top of my head. (I'm away from my computer)

stramel avatar Oct 12 '19 00:10 stramel

Hi @stramel, the part I was referring to as worsened is the instructions in TYPESCRIPT.md, specifically the idea of copying a types file from react-table into my project.

I was unaware that there were PRs for the missing types, thanks for letting me know 😀

hassankhan avatar Oct 12 '19 19:10 hassankhan

I found this file here: https://gist.github.com/Grsmto/1ac3a7ddb8ad8288660784a37bff1798

// Type definitions for react-table 7
// Project: https://github.com/tannerlinsley/react-table#readme
// Definitions by: Adrien Denat <https://github.com/grsmto>
//                 Artem Berdyshev <https://github.com/berdyshev>
//                 Christian Murphy <https://github.com/ChristianMurphy>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 3.0
declare module 'react-table' {
  import { Dispatch, SetStateAction, ReactNode } from 'react'

  export interface Cell<D> {
    render: (type: string) => any
    getCellProps: () => any
    column: Column<D>
    row: Row<D>
    state: any
    value: any
  }

  export interface Row<D> {
    index: number
    cells: Cell<D>[]
    getRowProps: () => any
    original: any
  }

  export interface HeaderColumn<D, A extends keyof D = never> {
    /**
     * This string/function is used to build the data model for your column.
     */
    accessor: A | ((originalRow: D) => string)
    Header?: string | ((props: TableInstance<D>) => ReactNode)
    Filter?: string | ((props: TableInstance<D>) => ReactNode)
    Cell?: string | ((cell: Cell<D>) => ReactNode)

    /**
     * This is the unique ID for the column. It is used by reference in things like sorting, grouping, filtering etc.
     */
    id?: string | number
    minWidth?: string | number
    maxWidth?: string | number
    width?: string | number
    canSortBy?: boolean
    sortByFn?: (a: any, b: any, desc: boolean) => 0 | 1 | -1
    defaultSortDesc?: boolean
  }

  export interface Column<D, A extends keyof D = never> extends HeaderColumn<D, A> {
    id: string | number
  }

  export type Page<D> = Row<D>[]

  export interface EnhancedColumn<D, A extends keyof D = never> extends Column<D, A> {
    render: (type: string) => any
    getHeaderProps: (userProps?: any) => any
    getSortByToggleProps: (userProps?: any) => any
    sorted: boolean
    sortedDesc: boolean
    sortedIndex: number
  }

  export type HeaderGroup<D, A extends keyof D = never> = {
    headers: EnhancedColumn<D, A>[]
    getRowProps: (userProps?: any) => any
  }

  export interface Hooks<D> {
    beforeRender: []
    columns: []
    headerGroups: []
    headers: []
    rows: Row<D>[]
    row: []
    renderableRows: []
    getTableProps: []
    getRowProps: []
    getHeaderRowProps: []
    getHeaderProps: []
    getCellProps: []
  }

  export interface TableInstance<D>
    extends TableOptions<D>,
      UseRowsValues<D>,
      UseFiltersValues,
      UsePaginationValues<D>,
      UseColumnsValues<D> {
    hooks: Hooks<D>
    rows: Row<D>[]
    columns: EnhancedColumn<D>[]
    getTableProps: (userProps?: any) => any
    getRowProps: (userProps?: any) => any
    prepareRow: (row: Row<D>) => any
    getSelectRowToggleProps: (userProps?: any) => any
    toggleSelectAll: (forcedState: boolean) => any
  }

  export interface TableOptions<D> {
    data: D[]
    columns: HeaderColumn<D>[]
    state?: [any, Dispatch<SetStateAction<any>>]
    debug?: boolean
    sortByFn?: (a: any, b: any, desc: boolean) => 0 | 1 | -1
    manualSorting?: boolean
    disableSorting?: boolean
    defaultSortDesc?: boolean
    disableMultiSort?: boolean
  }

  export interface RowsProps {
    subRowsKey: string
  }

  export interface FiltersProps {
    filterFn: () => void
    manualFilters: boolean
    disableFilters: boolean
    setFilter: () => any
    setAllFilters: () => any
  }

  export interface UsePaginationValues<D> {
    nextPage: () => any
    previousPage: () => any
    setPageSize: (size: number) => any
    gotoPage: (page: number) => any
    canPreviousPage: boolean
    canNextPage: boolean
    page: Page<D>
    pageOptions: []
  }

  export interface UseRowsValues<D> {
    rows: Row<D>[]
  }

  export interface UseColumnsValues<D> {
    columns: EnhancedColumn<D>[]
    headerGroups: HeaderGroup<D>[]
    headers: EnhancedColumn<D>[]
  }

  export interface UseFiltersValues {
    setFilter: () => any
    setAllFilters: () => any
  }

  export function useTable<D>(props: TableOptions<D>, ...plugins: any[]): TableInstance<D>

  export function useColumns<D>(props: TableOptions<D>): TableOptions<D> & UseColumnsValues<D>

  export function useRows<D>(props: TableOptions<D>): TableOptions<D> & UseRowsValues<D>

  export function useFilters<D>(
    props: TableOptions<D>,
  ): TableOptions<D> & {
    rows: Row<D>[]
  }

  export function useSortBy<D>(
    props: TableOptions<D>,
  ): TableOptions<D> & {
    rows: Row<D>[]
  }

  export function useGroupBy<D>(props: TableOptions<D>): TableOptions<D> & { rows: Row<D>[] }

  export function usePagination<D>(props: TableOptions<D>): UsePaginationValues<D>

  export function useFlexLayout<D>(props: TableOptions<D>): TableOptions<D>

  export function useExpanded<D>(
    props: TableOptions<D>,
  ): TableOptions<D> & {
    toggleExpandedByPath: () => any
    expandedDepth: []
    rows: []
  }

  export function useTableState(
    initialState?: any,
    overriddenState?: any,
    options?: {
      reducer?: (oldState: any, newState: any, type: string) => any
      useState?: [any, Dispatch<SetStateAction<any>>]
    },
  ): any

  export const actions: any
}

tsujp avatar Oct 13 '19 11:10 tsujp

@hassankhan That document is very new and still needs some revisions. We don't generally copying types except for maybe to use in an example or as a starting point. I'm still not sure what you are saying has regressed as the typescript documentation is brand new, I don't see how it could regress?

@tsujp That gist is very out of date and incompatible with the types that are going to be supported.

stramel avatar Oct 14 '19 16:10 stramel

Beta 12 doesn't work as-is with Types though, why can't the repo be redone with Typescript inline instead of separation of concerns that is currently the focus? Isn't this the perfect time?

I'd love to help out if I wasn't so average at Typescript, I only just started using it two months ago unfortunately.

tsujp avatar Oct 15 '19 07:10 tsujp

What exactly do you mean by "separation of concerns"? Do you mean that the types don't just lump in every hooks behavior? How do you deal with external hooks? How do you deal with hooks that are standard, but aren't included in the configuration of the table? These are all separate right now so that each user can tailor the interface so match what's supported.

I'll admit that this is a bit awkward, I don't think that anyone is particularly happy with it, but until we get a better solution that works for those use cases, I don't really see an alternative.

As a separate point, the interface is huge and changing (it is a beta after all), it's been very easy to miss stuff, so yes, there are apis that have been missing. But again, they can easily be added locally (using the same declaration merging technique) until they get added to the main types.

I'm not saying that we don't want this to be easier, we do, it's just not obvious what the right solution is and so we went with something that works until we can get something better.

ggascoigne avatar Oct 15 '19 16:10 ggascoigne

Chiming in here with a typing issue. I'm getting Property 'getSortByToggleProps' does not exist on type 'ColumnInstance<any>'. when trying to implement sortable columns in TypeScript. I've essentially copy/pasting the sorting example to get started here.

react-table version: 7.0.0-beta.12

Screenshot 2019-10-24 12 47 58

CodeSandbox here: https://codesandbox.io/s/react-table-beta-12-typings-xculv

kpollich avatar Oct 24 '19 17:10 kpollich

@kpollich I had the same issue. What you have to do, is to copy the file react-table-config.d.ts, inside a directory (I recommend copying it inside the directory as your table component). Then remove the interface you do not need or the extends you won't use.

Everything is explained here : https://github.com/tannerlinsley/react-table/blob/master/TYPESCRIPT.md

I hope this helps 😃

iamvimuserbtw avatar Oct 24 '19 18:10 iamvimuserbtw

~~The types at https://github.com/tannerlinsley/react-table/blob/master/TYPESCRIPT.md do not function properly.~~

prepareRow() is of type void and so the statement prepareRow(row) || ... is invalid. An expression of type void cannot be checked for truthiness. ~~Attempting to workaround this by turning it into (prepareRow(row), ...) is also invalid.~~

~~I haven't been able to use this library with the types present in the repo yet.~~

EDIT:

It seems I had the syntax wrong, a working example would be

{rows.map(
  (row, i) => (
    (prepareRow(row), (
      <tr {...row.getRowProps()}>
        // ... do stuff
      </tr>
    )))
)}

Instead of

{rows.map(
  (row, i) =>
    prepareRow(row) || (
      <tr {...row.getRowProps()}>
        // ... do stuff
      </tr>
    )
)}

tsujp avatar Nov 03 '19 10:11 tsujp

yeah, the problem is that the examples all do prepareRow() || ..., but prepareRow is actually void, you can check the code, it has no return.

That said, while it's a bit misleading, it is valid javascript so perhaps we should have defined prepareRow as returning undefined. It's not exactly what's going on, but it would have keep the usage in the examples working in typescript.

ggascoigne avatar Nov 03 '19 17:11 ggascoigne

Indeed I was just a bit thrown off as I am newly getting into TypeScript. All the examples are Javascript too so there will always be some differences I suppose. It's no bother now I think as the example in my previous comment is valid TypeScript as per:

  • https://eslint.org/docs/rules/no-sequences
  • https://github.com/Microsoft/TypeScript/issues/28248#issuecomment-434693307

tsujp avatar Nov 03 '19 18:11 tsujp

I'm specifically seeing a couple other bugs in the beta-12 types:

  • In UseRowSelectState, the selectedRows field is wrong. The code has a selectedRowPaths field
  • In UseRowSelectInstanceProps, the toggleRowSelected method appears to expect an array that it can call .join() on, not a single string

My hacky local fixes in our types customization file:

    // FIX The R-T type claims this is selectedRows, not selectedRowPaths
    export interface UseRowSelectState<D extends object> {
        selectedRowPaths: IdType<D>[];
    }

    // FIX The R-T type for toggleRowSelected says it takes a string, not an array
    export type UseRowSelectInstancePropsFixed<D extends object> = Omit<
        UseRowSelectInstanceProps,
        "toggleRowSelected"
    > & {
        toggleRowSelected: (rowPath: (string | number)[], set?: boolean) => void;
    };

markerikson avatar Nov 14 '19 23:11 markerikson

a) that's exactly how I fix these in my project. b) the selectedRowPaths change actually matches what's in master, by not shipped yet. c) the toggleRowSelected fix is new to me and looks like an unreported bug. I'll try to keep track of it.

ggascoigne avatar Nov 15 '19 03:11 ggascoigne

I'm getting the following error:

Object literal may only specify known properties, and 'disableMultiSort' does not exist in type 'TableOptions<object>'.

daviddelusenet avatar Nov 25 '19 12:11 daviddelusenet

Same for selectedFlatRows, isAllRowsSelected atm, no type definitions. @hassankhan can you link here the PRs that have these kind of missing types please?

zone-live avatar Nov 25 '19 16:11 zone-live

Same for selectedFlatRows, isAllRowsSelected atm, no type definitions. @hassankhan can you link here the PRs that have these kind of missing types please?

Look on UseRowSelectInstanceProps for those two, they are there.

ggascoigne avatar Nov 25 '19 16:11 ggascoigne

You mean here @ggascoigne ? https://github.com/tannerlinsley/react-table/blob/master/index.d.ts#L452 My index.d.ts is a bit different from that 🤔

index d ts   2019-11-25 17-10-52

zone-live avatar Nov 25 '19 17:11 zone-live

I'm guessing that you're using beta.12 or earlier, that definition was added for beta.13 or later.

ggascoigne avatar Nov 25 '19 17:11 ggascoigne

Yap, that's it @ggascoigne thanks! 👍

zone-live avatar Nov 25 '19 20:11 zone-live

I'm using beta.12 and this is how I include plugins to react-table types, it's really simple:

declare module 'react-table' {
  interface Row<D> extends UseExpandedRowProps<D> { }
  interface Column<D extends object = {}> extends UseSortByColumnOptions<D> {}
  interface ColumnInstance<D extends object = {}> extends UseSortByColumnProps<D> { }
  interface TableOptions<D extends object = {}> extends UseSortByOptions<D> { }
}

soanvig avatar Nov 26 '19 10:11 soanvig