Skip to content

Easier access to scale types #8731

Closed
@joshkel

Description

@joshkel

I've split my chart creation logic into several functions to make it easier to maintain, and I use TypeScript type definitions on the individual pieces to keep them manageable.

In Chart.js 3.0.0 beta 7, this was simple:

function createXAxisScale(range: number): ScaleOptions<'linear'> {
  const tickCount = 8;
  return {
    type: 'linear',
    min: 0,
    suggestedMax: range,
    ticks: { stepSize: range / tickCount },
  };
}

In rc.3, it got a bit more verbose:

function createXAxisScale(range: number): ScaleOptionsByType<'linear'> {
  const tickCount = 8;
  return {
    type: 'linear',
    min: 0,
    suggestedMax: range,
    ticks: { stepSize: range / tickCount },
  };
}

In rc.5, since partial was removed in #8717, this now complains if any properties of ScaleOptions are missing.

I can handle this by using Partial<ScaleOptionsByType<'linear'>>, but since this is a common pattern in my code, I wondered if it would be worth having a type within Chart.js to make it easier.

Possible solutions:

  • Reintroduce DeepPartial within ScaleOptionsByType.
    export type ScaleOptionsByType<TScale extends ScaleType = ScaleType> =
      { [key in ScaleType]: { type: key } & DeepPartial<ScaleTypeRegistry[key]['options']> }[TScale]
    ;
    
  • Introduce a type alias for convenience:
    export type ScaleOptions<TScale extends ScaleType = ScaleType> = Partial<ScaleOptionsByType<TScale>>;
    

If I'm better off using Partial or adding a ScaleOptions in my own code, that's fine, but since it seemed like a possibly unintended result of #8717, I wanted to check. Thanks!

Demo: https://codesandbox.io/s/chartjs-partial-scale-bjt4e?file=/src/index.ts

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions