0👍
If nothings seems to work you can disable type checking for a particular line by adding following comment (only if there is no other way to just work around with it)
// ...other styles
// @ts-ignore: Unreachable code error
backgroundColor: gradientFill
? gradientFill
: chartRef.current.data.datasets[0].backgroundColor,
//...other styles
0👍
It’s possible that chartRef.current
is not defined, so you need to check that it exists before you can access the data
property on it:
backgroundColor:
chartRef?.current?.data?.datasets
? chartRef.current.data.datasets[0].backgroundColor
: gradientFill,
I would also recommend moving the definition of chartRef
to be above the formatData
function which accesses it.
0👍
Object is possibly ‘null’.
That is actually correct. In fact, the type of chartRef
is React.MutableRefObject<Chart | null>
, thus it’s current
property is either a Chart
or null
. If you are sure it will not be null when accessing the getter, you can use the non-null assertion operator, ie. !
. So you’d do this:
chartRef.current!
Here, you are allowed to call methods on it, or access properties, eg. data
.
However, you’ll see that dataset
may be undefined
. Therefore, you should either implement some conditional logic to check if it has a value, or — again — if you are sure it will have a value, then use the same operator:
backgroundColor: gradientFill
? gradientFill
: chartRef.current!.data.datasets![0].backgroundColor
- [Chartjs]-Chart.js – data points get smaller after hover
- [Chartjs]-Chartjs show dot point on hover over line chart