chartjs / chartjs-plugin-annotation

Annotation plugin for Chart.js

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Type error with backgroundColor on options parameter for scriptable options

thomas-haufe opened this issue · comments

@thomas-haufe Thank you for feedback. The options passed by context need to be cast to the options related to the annotation type where the scriptable option is invoked. By default a annotation for line is used but line annotation doesn't have the backgroundColor as options.

The following code could solve the issue:

import { Chart, ChartData, ChartOptions, Color } from 'chart.js';
import annotationPlugin, {BoxAnnotationOptions} from 'chartjs-plugin-annotation';

Chart.register(annotationPlugin)

const options: ChartOptions<'bubble'> = {
  plugins: {
    annotation: {
      annotations: {
        firstQuadrantBg: {
          type: 'box',
          backgroundColor: '#fff',
          borderColor: (_, options) => {
            const boxOptions = options as BoxAnnotationOptions;
            return boxOptions.backgroundColor as Color;
          },
        }
      }
    }
  }
}

Thanks for the idea @stockiNail. Are you proposing it as a final solution or as a temporary workaround until this is fixed properly?

I think this should be the job of the library and not the job of the consumer.

And it's probably possible to let chartjs correctly infer the type with some advanced type gymnastics? :)

@thomas-haufe currently the plugin is designed to cast the options when engaged in a scriptable options.
That said, this is a workaround till the scriptable context will be extended maybe in this lib to add the type.

Wouldn't it work to change the following line

export type Scriptable<T, TContext> = T | ((ctx: TContext, options: AnnotationOptions) => T);

to something like this?
export type Scriptable<T, TContext, TYPE> = T | ((ctx: TContext, options: AnnotationOptions[TYPE]) => T); (or something similar)?