Skip to content

typescript type incorrect for chart.update(mode) #11487

@Cazka

Description

@Cazka

Expected behavior

the type of the parameter mode here:

update(mode?: UpdateMode): void;

should allow a function aswell.

In this method which is called by chart.update, the parameter mode is checked if it is a function.

this._updateDataset(i, isFunction(mode) ? mode({datasetIndex: i}) : mode);

Current behavior

The current type definition of the parameter mode is UpdateMode:

export declare enum UpdateModeEnum {
resize = 'resize',
reset = 'reset',
none = 'none',
hide = 'hide',
show = 'show',
default = 'default',
active = 'active'
}
export type UpdateMode = keyof typeof UpdateModeEnum;

Reproducible sample

https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAbzgYQBYENZwL5wGZQQhwDkAxhrAHQBWAziQNwCwAUGwG6ZxkwAecALxwAJhDIBXEAFMAdjCoBzaTACiAG2kz5AIQCeASREAKAEQg9aTDFMBKOOjpwAEgBUAsgBlk6WVzoaWnIwLKxcUHAWVljCstIA7iiUMMa8fAA0iGxwOXAwemDSAFyk6sBxJOnZuSLoMOglCNW5ueroAEbS6nQlANqmAErSIqaZpjrqEtKjcKYAml3qEPEzpgDiUNJyqwAKElBgmqsA8lC+yqYAulWsLS219XQqPXC9Tbd3n22d6iUkAMRwCB4OAANQgMGkDBun0+DwarwAjAAmTKIgCcmQAzJkAKyZVFwLHXZp3bCXUnYG7YWyhNhRZJUCRgB7SYypfiNUR1RwqAyyETSPglWRSToRGlCAB8cAA9AAqOCyCFweLQADW5UU8tltKAA

Optional extra steps/info to reproduce

No response

Possible solution

change the type of mode to a union type: UpdateMode | ((ctx: { datasetIndex: number }) => UpdateMode)

Context

I stumpled across this issue when trying to change the visibility of multiple datasets with one legend label.

my solution required passing a function to chart.update in the overwritten plugins.legend.onClick method:

onClick(e, legendItem, legend) {
  const isNowVisible = !legend.chart.isDatasetVisible(legendItem.datasetIndex);
  const mode = isNowVisible ? 'show' : 'hide';

  if (isNowVisible) {
    legend.chart.show(legendItem.datasetIndex);
    legend.chart.show(anotherIndex);
  } else {
    legend.chart.hide(legendItem.datasetIndex);
    legend.chart.hide(anotherIndex);
  }

  (legend.chart as any).update((ctx: { datasetIndex: number }) => [legendItem.datasetIndex, anotherIndex].includes(ctx.datasetIndex) ? mode : undefined);
}

chart.js version

v4.4.0

Browser name and version

No response

Link to your project

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions