Home > front end >  Object is possibly 'null' react typescript
Object is possibly 'null' react typescript

Time:12-28

I am making a chart in react app with typescript and implementation wise things are completed.

Issue is that I am receiving the error in the line,

backgroundColor: gradientFill
          ? gradientFill
          : chartRef.current.data.datasets[0].backgroundColor,

Error states that,

Object is possibly 'null'.

Working Example:

Edit Chart.js React Typescript (forked)

Error occurs in line number 24 .

Things tried:

chartRef?.current?.data.datasets[0].backgroundColor

This results in the error Property 'data' does not exist on type 'never'..

Could you please kindly help me to get rid of the error? Thanks in advance.

Context: This question is related to my previous question and this answer.

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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.

  • Related