Home > OS >  Property 'getLabelForValue' does not exist on type in Chart.js
Property 'getLabelForValue' does not exist on type in Chart.js

Time:02-16

I have an error in callback method

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

How to fix this problem?

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: {
        // <--------- error is here --------->
        callback(val: number, index: number): string {
          return index % 2 === 0 ? this.getLabelForValue(val) : '';
        },
        color: 'red',
        maxRotation: 0,
        minRotation: 0,
      }
    }
  }
},

CodePudding user response:

COnsider this example:

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): string {
          return index % 2 === 0 && typeof val === 'number' ? this.getLabelForValue(val) : '';
        },
        color: 'red',
        maxRotation: 0,
        minRotation: 0,
      }
    }
  }
};

Playground

The problem is that val argument in callback might be a string whereas getLabelForValue expects only number. First of all, get rid of explicit types in callback method and check whether val is number

  • Related