'Chart.js 3.x custom positioners: cannot use them in TypeScript

I'm using ChartJS v3 and I'm trying to implement a custom tooltip positioner, as described in the docs:

https://www.chartjs.org/docs/master/configuration/tooltip.html#position-modes

However, the problem is that I'm coding in TypeScript and the type checking is fighting me over this. The first problem is that I cannot define the custom positioner like in the example:

const tooltipPlugin = Chart.registry.getPlugin('tooltip');
tooltipPlugin.positioners.myCustomPositioner = ...

because the type returned by getPlugin() does not contain the positioners property.

The second problem is when you then have to configure the plugin. I cannot do this:

plugins: {
    tooltip: {
      position: 'myCustomPositioner',
      ...
    }
}

because the position property only accepts the defaults built in values ('average' and 'nearest') but does not take a custom string.

How do I work around this? I wasa happy that the latest ChartJS provides strong types, but they are no use if the make core features of the library unusable... what am I missing?



Solution 1:[1]

The proper way to do this is to extend the positioners map typings to include your custom function. Refer to https://www.chartjs.org/docs/3.4.1/developers/charts.html, which includes how to extend the typings for custom charts, it is similar to this.

By just casting the position, as the solution from @bangash, you are tricking the compiler. That solution also does not solve the problem when you create the positioner.

Note: This expects you are using ChartJS 3.x

Create a file called chartjs.d.ts somewhere in your project that tsconfig.json reads from, for example @types/chartjs.d.ts

import type { TooltipPositionerFunction } from 'chart.js';

declare module 'chart.js' {
  // Extend tooltip positioner map
  interface TooltipPositionerMap {
    cursor: TooltipPositionerFunction<ChartType>;
  }
}

Then, create your function where you are registering your components:

import { Tooltip } from 'chart.js'

// Create positioner to put tooltip at cursor position
Tooltip.positioners.cursor = function (chartElements, coordinates) {
  return coordinates;
};

Now you can use your cursor as position property of the tooltip.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1