"Why is it that the onChange method of the antd table does not return an array of numbers for selectedRowKeys

In my current project, I am working on a Nextjs application that utilizes typescript and antd.

The application includes a table component from antd which allows users to select rows.

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

The output shows: [12, 11, 10]

This is an array of numbers.

However, when I change it to 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 is this happening?

Answer №1

After reviewing the antd documentation concerning rowSelection, it's clear that the onChange function accepts three parameters: selectedRowKeys, selectedRows, and info:{ type }. It's important to note that the type of selectedRowKeys is string[]|number[].

If you define it as any[], there won't be any issues. However, if you specify selectedRowKeys[] as number[], errors may arise when onChange is called with non-numeric values (such as an array of strings).

In summary, consider using selectedKeys = string[]|number[] instead.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the steps to fix the error stating that 'loginError.data' is an unknown type?

Recently delving into typescript, I decided to test the waters with nextjs, rtk query, and antd. However, while attempting to access error within useLoginMutation using the property error.data.message, it was flagged as type unknown. To tackle this issue, ...

Encountering the Firebase issue with error code (auth/invalid-api-key)

I keep encountering the error message 'Firebase: Error (auth/invalid-api-key) ' despite having entered all the correct authentication details. ...

Does having an excessive amount of variable declarations result in a noticeable decline in performance?

One thing I notice for the sake of readability is that I tend to create new variables for data that I already have on hand. I'm curious, does this impact performance significantly? Here's an example of what I mean: const isAdult = this.data.per ...

How to display a modal within a router-link in Vue 3?

Below are buttons with router-links. However, I only want the calculator button to open a modal. When I execute the code provided, all buttons trigger the modal instead of just the calculator button. Output: https://i.sstatic.net/layQ1.png Router-link C ...

Is the SWR cache stored on the client-side or server-side?

In my current project with Next JS and SWR, I am curious about the storage location of SWR's cache. Does it reside on the client side or the server side? This question is important to me because if the cache is stored on the client side, I can confid ...

How can I send 'blocking' parameter to getStaticPaths function in Next.js using TypeScript?

Whenever I try to use fallback: 'blocking', in my Next.js page, TypeScript throws an error. I am using the latest 12.2.0 version of Next.js. What could be causing this issue? Type '() => Promise<{ paths: any; fallback: string; }>&ap ...

Eliminating Tailwind typography with PurgeCSS in a next.js project

Building a next.js site and utilizing specific text like the code snippet below: const defaultTheme = require('tailwindcss/defaultTheme') module.exports = { theme: { extend: { fontFamily: { sans: ['SFMono-Regular', ...

What is the best way to configure Jenkins to exclude or include specific component.spec.ts files from being executed during the build

Currently, I am facing an issue while attempting to include my spec.ts files in sonarqube for code coverage analysis. However, my Jenkins build is failing due to specific spec.ts files. Is there a way to exclude these particular spec.ts files and include ...

The error `TypeError: Unable to access properties of an undefined value (reading 'authService')` occurred

I'm attempting to check if a user is already stored in local storage before fetching it from the database: async getQuestion(id: string): Promise<Question> { let res: Question await this.db.collection("questions").doc(i ...

Next.js API is throwing a TypeError because req.formData is not a recognized function

Below is the code snippet for the Next.js route I am working on: import { NextRequest, NextResponse } from 'next/server'; export const config = { runtime: 'edge', }; export default async function POST(req: NextRequest): Promise< ...

What made the "in" operator not the best choice in this situation?

When I set out to create a type that represents the values of a given object type, I initially came up with this: type Book = { name:string, year:number, author:string } // expected result "string" | "number" type ValueOf<T ex ...

Detecting worldwide route adjustments in Nextjs 13

Is there a way to detect when my route changes in order to trigger a specific event? I want to be able to handle this change and take action accordingly. I am currently facing challenges with Nextjs 13 and its implementation of the app router. As per best ...

Identify the general type according to a boolean property for a React element

Currently, I am facing a scenario where I need to handle two different cases using the same component depending on a boolean value. The technologies I am working with include React, Typescript, and Formik. In one case, I have a simple select box where th ...

Encountering an internal server error when using Next.js API routes with Nodemailer

Using cPanel to host my Next.js website, I encountered an issue with an API route that uses Nodemailer to send messages. While the route works perfectly fine on localhost and Vercel, every time I call it on the live server, I receive an internal server err ...

Searching Firebase by using comparison operators on various fields

const FindFiis = async () => { const data: any[] = []; // Firebase query with inequalities on different fields to retrieve docs. // Objective: Select documents where dividendYield is between 8 and 20 and pvp is less than or equal to 1. ...

JavaScript Looping through multiple files for upload will return the last file in the series

I'm currently working on implementing a multiple file upload feature using JavaScript. Within my HTML, I have the following input: <input type="file" (change)="fileChange($event,showFileNames)" multiple /> When the onChange event is triggere ...

While running tslint in an angular unit test, an error was encountered stating 'unused expression, expected an assignment or function call'

Is there a method to resolve this issue without needing to insert an ignore directive in the file? Error encountered during command execution: ./node_modules/tslint/bin/tslint -p src/tsconfig.json --type-check src/app/app.component.spec.ts [21, 5]: unuse ...

Getting js.map Files to Function Properly with UMD Modules

I am experiencing an issue with debugging TypeScript files in Chrome and Firefox. Specifically, when trying to debug the MapModuleTest.ts file, the debugger seems to be out of sync with the actual JavaScript code by two lines. This discrepancy makes settin ...

Issues arise due to data inconsistency stemming from the combination of a for loop and .map() function within the BACK4APP

I seem to be facing a challenge with data consistency caused by the for (const object of results) {} loop in the Sandbox Link at line41. The issue is that the results are displayed as a single result after using the .map() method. However, when I perform a ...

Tips for showing information exclusively while hovering over an item

I tried to mimic the functionality seen on GitHub, where icons appear when hovering over headings. import remarkGfm from 'remark-gfm'; import rehypeSlug from 'rehype-slug' import rehypeAutolinkHeadings from "rehype-autolink-heading ...