Chart.js icon indicating copy to clipboard operation
Chart.js copied to clipboard

Options properties with defaults have to be assigned

Open petronellius opened this issue 2 years ago • 5 comments

Expected Behavior

Properties that have default values should be optional.

Current Behavior

I'm migrating a project from 2.5 to 3.6 and having a problem to transpile TypesScript code with options of types like CartesianScaleOptions, TickOptions, FontSpec etc.

Possible Solution

Optional properties. https://www.typescriptlang.org/docs/handbook/interfaces.html#optional-properties

Steps to Reproduce

The problematic options declarations are at the end of file of TS playground

Context

Environment

  • Chart.js version: 3.6.0
  • TypeScript version: 4.5.2

petronellius avatar Nov 24 '21 11:11 petronellius

This is interesting. The reason it happens is because CartesianScaleOptions is more of an internal type. For example, the category options are:

export type CategoryScaleOptions = CartesianScaleOptions & {
  min: string | number;
  max: string | number;
  labels: string[] | string[][];
};

We only make the properties optional when types go through DeepPartial<T>. Is there a reason to use the CartesianScaleOptions type directly? It might make sense to make a new type DeepPartial<CartesianScaleOptions> as a work-around

etimberg avatar Nov 28 '21 19:11 etimberg

Sure, I could create object of DeepPartial<CartesianScaleOptions> type. But this is not what I really want. If I create an object of DeepPartial<CartesianScaleOptions>, I can omit even mandatory properties. I would expect types to guard which property has to be defined and which can be omitted. Is there any reason not to define optional properties?

petronellius avatar Nov 29 '21 08:11 petronellius

@petronellius what would be a mandatory property? I don't think there is anything mandatory, because the options are backed by defaults from chart type and scale type.

kurkle avatar Nov 29 '21 10:11 kurkle

If there are no mandatory properties, using DeepPartial will be fine too. I have been confused because some properties are already defined as optional (stack, stackWeight, etc).

petronellius avatar Nov 29 '21 16:11 petronellius

I'm not quite sure how this should be handled. Should we aim to remove the DeepPartial for option types and mark everything optional, or should we export these kind of types withDeepPartial applied?

I think it could be better for typescript complexity and thus performance if DeepPartial was not used, but I might be missing a thing or two from my thoughts.

kurkle avatar Jan 12 '22 04:01 kurkle