Chart.js is indicating that there is no 'getLabelForValue' property available for this type

My callback method is throwing an error

TS2322:... Type `string | number` is not assignable to type `number`.               Type `string` is not assignable to type `number`.

Any suggestions on how to resolve this issue?

import { ChartOptions } from "chart.js"

const options: ChartOptions = {
  responsive: true,
  interaction: {
    mode: 'index',
    intersect: false,
  },
  elements: {
    point: {
      radius: 1,
      pointStyle: 'circle',
      hoverRadius: 2,
      hoverBorderWidth: 3,
    },
    line: {
      fill: true,
    },
  },
  scales: {
    x: {
      ticks: {
        // <--------- the error occurs here --------->
        callback(val: number, index: number): string {
          return index % 2 === 0 ? this.getLabelForValue(val) : '';
        },
        color: 'red',
        maxRotation: 0,
        minRotation: 0,
      }
    }
  }
},

Answer №1

Let's examine this scenario:

import { ChartOptions } from "chart.js"

const options: ChartOptions = {
  responsive: true,
  interaction: {
    mode: 'index',
    intersect: false,
  },
  elements: {
    point: {
      radius: 1,
      pointStyle: 'circle',
      hoverRadius: 2,
      hoverBorderWidth: 3,
    },
    line: {
      fill: true,
    },
  },
  scales: {
    x: {
      ticks: {
        callback(val, index) {
          return index % 2 === 0 && typeof val === 'number' ? this.getLabelForValue(val) : '';
        },
        color: 'red',
        maxRotation: 0,
        minRotation: 0,
      }
    }
  }
};

Interactive Demo

An issue arises when the val parameter in the callback may be a string rather than the expected number for getLabelForValue. To address this, remove explicit typings from the callback method and verify if val is indeed a number.

Answer №2

scales: {
        xAxes: [{

            gridLines: {
                display: false
            },
            ticks: {
                beginAtZero: true,

                callback: function(value, index, values) {
                    return value.substr(0, 12);
                },

            },
        }],

did the trick for me

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's the best approach for revalidating data with mutate in SWR?

Whenever a new album is created in my app, the post request response includes an updated list of all albums. To enhance the user experience, I wanted the newly created content to automatically show up without requiring a page refresh. Although I am famil ...

Angular version 8.2 combined with Firebase can result in errors such as those found in the `./src/app/app.module.ngfactory.js` file towards the end of the process when attempting to build with

My first time posing a query on this platform, and certainly not my last. The issue at hand involves the ng-build --prod process failing to complete and throwing errors in my Angular 8.2.14 application. I've integrated Firebase into my project succes ...

Utilizing Union type and static declarations instead of String Enum

In my opinion, the following approach works better in TypeScript compared to using Enums. I am looking for a way to simplify this process, perhaps by using a utility type. It would be ideal if we could define Enums to function in a similar way, but unfortu ...

Creating a date format for a REST API using Typegoose and Mongoose

Currently, I am utilizing TypeScript for a server that is connected to a MongoDB database. To ensure consistency, I am defining the outputs using an OpenAPI file. When working with Mongoose, I have experience in defining dates like this: birthday: Dat ...

Utilizing VSCode extension for direct implementation of multi-step input functionality

One of the challenges I am facing is using the multi-step input directly, where the user can choose option F1 to initiate the steps for selecting items. I came across an example which demonstrated this functionality without including quickOpen and basic i ...

Leveraging information sourced from Observable Angular 2

Let me start by expressing my gratitude towards the community for always being supportive of learners like myself as we dive into new technologies. I have been delving into Angular lately, and there is a specific aspect that still puzzles me, one that does ...

Just a straightforward Minimum Working Example, encountering a TypeScript error TS2322 that states the object is not compatible with the type 'IntrinsicAttributes & Props & { children?: ReactNode; }'

Currently, I am immersed in a project involving React and Typescript. I am grappling with error code TS2322 and attempting to resolve it. Error: Type '{ submissionsArray: SubmissionProps[]; }' is not assignable to type 'IntrinsicAttributes ...

Webpack 2.7.0 throws an error: "Unexpected parameter: theme"

At the moment, I am on webpack 1.16.0 and using --theme as an argument to set the output path and plugin paths. The command appears as: rimraf dist && webpack --bail --progress --profile --theme=<name of theme> However, as I try to upgrade ...

Navigating Circular Relationships in TypeScript

Herein lies a question about statically inferring the signature of runtime types, as seen in popular libraries like zod and io-ts. If you want to see an example in action, check out this TS playground link. Let's say we're attempting to model t ...

Utilizing useRouteMatch with strongly-typed react-router components

When retrieving the match from my route using the hook in this manner: const match = useRouteMatch('/chat/:id'); I then intend to pass it down to a child component. However, when I attempt to do so, I encounter the following error: Type ' ...

Have you ever wondered why querySelectorAll('div') gives back a list of HTMLDivElement elements, while querySelectorAll('div.className') provides a list of Element elements in TypeScript?

I've been pondering why, when a class name is added to querySelectorAll, the type no longer shows up as HTMLDivElement. document.querySelectorAll('div').forEach(item => { // item type is HTMLDivElement }); document.querySelectorAll(& ...

Generate a React App with TypeScript: Only transpile, skip type checking and linting

Need help optimizing the deployment of my small React project on a Google Compute Engine instance with limited RAM of under 1.5 GB. During the production build, the typescript linter and compiler consistently consume around 2 GB of RAM, which causes the C ...

Tips for bringing in a class that has been exported from a module

I have a typescript file (generated) that is being used in my angular project. The contents of this file called contracts.ts are as follows: export module A.B.C.Models { export class Activity { prop1: number; ... } } I am attempting to use t ...

Angular is throwing an error stating that "ctx" is not defined

Struggling with a weather app using the OpenWeatherMap API, I've encountered service blocking issues twice already due to excessive requests. Despite thoroughly checking my code multiple times, I can't pinpoint any specific loop causing server ov ...

The Ag Grid Cell Render feature is not available

I have been working on creating my own cell renderer by referring to this example https://www.ag-grid.com/javascript-data-grid/cell-rendering/, but I am running into an issue when using TypeScript. When I define a class that implements the ICellRenderer in ...

Sharing data between two unrelated components in Angular 4

I have an inquiry regarding passing data in Angular. Unlike the usual structure of <parent><child [data]=parent.data></child></parent>, my structure is different: <container> <navbar> <summary></summary& ...

Issue with DTO and a custom decorator in NestJS

I am currently facing an issue with using a DTO alongside a custom decorator within a NestJS controller for body validation. I am sending a request using multipart/form data, which requires me to parse the data from a string to JSON. However, when attempti ...

Adjusting the dimensions of the cropper for optimal image cropping

I am currently working on integrating an image cropper component into my project, using the react-cropper package. However, I am facing a challenge in defining a fixed width and height for the cropper box such as "width:200px; height:300px;" impo ...

React-leaflet with TypeScript is failing to display GeoJSON Points on the map

I am attempting to display points on a map using geojson points in my react application with react-leaflet. However, for some unknown reason, the points are not rendering on the map. When I try importing a JSON file, I encounter an error: TS2322: Ty ...

How to fetch a file from a Spring Boot server using Angular 4

I'm currently developing a Spring Boot server with an Angular 4 front-end. I've created a service that allows users to download a .zip file from the front-end using HttpClient. Below is my code: Angular service: getZip(fileName: string) : Obser ...