Search code examples
typescriptnext.jsantd

Why selectedRowKeys in onChange of table antd is not a number array?


I work in a Nextjs project with typescript and antd.

I use a table of antd and user can select row.

const rowSelection = {
  onChange: (selectedKeys: any[], selectedRows: Mission[]) => {
    console.log(selectedKeys);
  }
}

the result: [12, 11, 10]

It's a number array.

but if I change into selectedKeys: number[]:

Type '{ onChange: (selectedKeys: number[], selectedRows: Mission[]) => void; getCheckboxProps: (record: Mission) => { disabled: boolean; }; }' is not assignable to type 'TableRowSelection<Mission>'.
  Types of property 'onChange' are incompatible.
    Type '(selectedKeys: number[], selectedRows: Mission[]) => void' is not assignable to type '(selectedRowKeys: Key[], selectedRows: Mission[], info: { type: RowSelectMethod; }) => void'.
      Types of parameters 'selectedKeys' and 'selectedRowKeys' are incompatible.
        Type 'Key[]' is not assignable to type 'number[]'.
          Type 'Key' is not assignable to type 'number'.
            Type 'string' is not assignable to type 'number'.ts(2322)
Table.d.ts(22, 5): The expected type comes from property 'rowSelection' which is declared here on type 'IntrinsicAttributes & TableProps<Mission> & { children?: ReactNode; } & { ref?: Ref<HTMLDivElement> | undefined; }'

Why?


Solution

  • Looking at antd documentation on rowSelection, onChange accepts 3 params which are selectedRowKeys, selectedRows and info:{ type }. And if you read again on selectedRowKeys, the type is string[]|number[].

    Obviously if you typed it as any[] then there will be no problem. But if you typed selectedRowKeys[] as number[], you may encounter error as onChange could be called with values that are not numbers (e.g. an array of strings).

    TLDR, try selectedKeys = string[]|number[] instead.